svelte-apollo icon indicating copy to clipboard operation
svelte-apollo copied to clipboard

Change authorization header after initial render?

Open Maximilian5189 opened this issue 3 years ago • 3 comments

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.

Maximilian5189 avatar Mar 30 '21 09:03 Maximilian5189

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

flashspys avatar Apr 11 '21 21:04 flashspys

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?

Maximilian5189 avatar Apr 23 '21 13:04 Maximilian5189

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

flashspys avatar Apr 24 '21 13:04 flashspys