'Sending Auth token in URQL query
I'm trying to send the token inside URQL token but there is no method or description in the docs. I've the token stored in my localStorage using localStorage.set() method.
Anyone has any idea how to send the auth token inside query or header?
I tried sending the auth using header and bearer option, but it didn't work.
Solution 1:[1]
Tokens are usually transmitted through the Authorization request header, in a format recognized/expected by your GraphQL back-end (usually in the form Authorization: Bearer <token>). You can do this during client creation/setup through the fetchOptions option (as this will indeed be passed on internally to fetch when making calls to your back-end).
Say your token is available and stored under localStorage.set("myToken", token), then you would set up your client like this:
const client = createClient({
url: 'http://localhost:3000/graphql', // <- your back-end URL
fetchOptions: () => {
const token = localStorage.get("myToken");
return {
headers: { authorization: token ? `Bearer ${token}` : '' },
};
},
});
See URQL's client setup documentation for Svelte for reference.
An alternative, more advanced option would be to make use of the Authentication exchange as part of the exchange chain you can use in an URQL setup (along with caching, dedup, etc.). I have not experimented with it myself, but it looks fairly straightforward if somewhat more complex.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Thomas Hennes |
