timhall / svelte-apollo

Svelte integration for Apollo GraphQL
MIT License
944 stars 69 forks source link

Change authorization header after initial render? #87

Open Maximilian5189 opened 3 years ago

Maximilian5189 commented 3 years ago

Hi,

my use case is the following: We have a homepage, where the user logs in with his credentials. Afterwards, a token is received, which should be used in the ApolloClient.

The token is stored for one hour. During that time, if the user reloads the page, the ApolloClient can be set up on page load with that token. That works fine.

However, on initial login, the token is received after mounting all components, when the user submits his credentials. The ApolloClient is set up beforehand synchronously on page load with setClient. So then, after the user logs in, the authorization header of the client has to be updated with the respective token. Is there already a way to this?

Many thanks in advance.

flashspys commented 3 years ago

Please have a look at the apollo documentation on this topic. There you can see how a authLink is added to supply Apollo with the auth credentials

Maximilian5189 commented 3 years ago

Yes thank you for the link. I did that and as described there works just fine.

My use case is a bit different however: on page load, the user is not signed in yet. Then the user logs in, the token is retrieved and can only then be added. At this point, setClient cannot be invoked anymore (error message: Function called outside component initialization).

I was figuring this means that the ApolloClient has to be created on page load and then setClient has to be called on page load as well.

Now i am wondering if svelte-apollo has any API to set the token of the client after the page has been loaded and the client already created?

flashspys commented 3 years ago

You shouldn't use setClient more than once, as you do not need to create a new client if you only want to change the AuthToken. The documentation I linked above mentions a ContextLink, created by setContext(…). The function you give to setContext is executed before each request. There you can provide your authorization header that you take from a central point in your application e.g. window.localStorage or a Svelte Store.

In short: After login save your token somewhere -> execute a new gql request -> the ContextLink callback gets fired -> get the previously saved token and put it into the authorization header -> request should succeed