Akryum / Akryum/vue-cli-plugin-apollo

Authlink runs before other links, preventing token refresh

Open
#310 1 comment 0 reactions 0 assignees View on GitHub
Dominant language
JavaScript
Stars
477
Forks
109
PR merge metrics
No merged PRs in 30d

Description

I'm using https://github.com/newsiberian/apollo-link-token-refresh to refresh my tokens. The process works fine, but the new access token won't be send in the request because authLink has already executed. It will work in the following requests.

### How it should work
1. GraphQL request starts
1. Refresh link detects access token has expired
1. Refresh link retrieves a new access token. Token is saved in localStorage
1. AuthLink sets the authorisation header from localStorage. New access token is used, the request will work

### How its working
1. GraphQL request starts
1. AuthLink sets the authorisation header from localStorage. Old expired access token is set
1. Refresh link detects access token has expired
1. Refresh link retrieves a new access token. Token is saved in localStorage
1. Request is sent with old token, so it fails.
1. Following requests will work, as now AuthLink will load the new token

### Possible solution
In [this issue](https://github.com/newsiberian/apollo-link-token-refresh/issues/2) from [apollo-link-token-refresh](https://github.com/newsiberian/apollo-link-token-refresh) is clearly stated that the link that performs the header setting (authLink) should be run last.

From the source code, I see that [authLink is being concatenated before all the other links](https://github.com/Akryum/vue-cli-plugin-apollo/blob/dfbad34582c2a5042e71ec2daacef69efd9be793/graphql-client/src/index.js#L87). Is it possible to concatenate it last? Will this break other functionality?

### Work Around
I've worked around this limitation by re-implementing the authLink and adding it after the refresh link.
```js
const accessTokenLink = setContext((_, { headers }) => {
// get your token
const token = localStorage.getItem(AUTH_TOKEN)

// add token to request headers
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : null
}
}
})
const link = ApolloLink.from([tokenRefreshLink, accessTokenLink ])
```

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.