
Security News
Feross on the 10 Minutes or Less Podcast: Nobody Reads the Code
Socket CEO Feross Aboukhadijeh joins 10 Minutes or Less, a podcast by Ali Rohde, to discuss the recent surge in open source supply chain attacks.
apollo-link-jwt
Advanced tools

An Apollo Link utility to handle JWT Authorization requests by automatically setting the headers with the access token and handling the refresh logic when the access token expires.
The package automatically detects when an access token has expired using JWT decode to keep the secret out of the client. It works with any existing endpoint that returns a new access token and refresh token from a provided refresh token by using a callback to handle any response structure.
Note: This package supports tokens stored in async-storage or any other manner of async lookup, helpful for React Native projects
npm i apollo-link-jwt
Note: Apollo V3 is a required peer depedency expected to be installed in your project already
const httpLink = createHttpLink({
uri: GRAPHQL_API,
});
/**
* Create Apollo Link JWT
*/
const apolloLinkJWT = ApolloLinkJWT({
apiUrl: 'https://your-api-url',
getTokens: async () => {
const accessToken = await AsyncStorage.getItem('ACCESS_TOKEN');
const refreshToken = await AsyncStorage.getItem('REFRESH_TOKEN');
return { accessToken, refreshToken };
},
fetchBody: async () => {
// Define fetch query
const query = {...};
return { query };
},
onRefreshComplete: async (data) => {
// Parse 'data' to extract the tokens from your existing refresh token API response
// Handle errors if fetch failed, call existing methods such as signOut();
...
return { newAccessToken, newRefreshToken };
},
});
return new ApolloClient({
link: from([
apolloLinkJWT,
httpLink, // Add terminating link last
]),
});
This utility will set the Authorization: Bearer token headers on requests when an access token is provided. This scheme is described by the rfc6750
Becasue handling JWT in the client should be an easy process and consistently handled across projects using Apollo Client. In addition, there are many times when you will want to provide an access token and refresh token stored in AsynStorage (if you're using React Native), which requires async support by the utlity. With Apollo Link JWT, you can pass async functions which get the tokens on the client with aysnc support.
The premise is simple:
The manual process of checking the access tokens expiration should be done in the client before every network request so an unnecessary network request is not made once it's expired. We can use JTW Decode here because we're only validating the token expiration time, even if this was faked by the user, it would only trigger a refresh token lookup sooner than expected.
| Attribute | Required | Async | Default | Description |
|---|---|---|---|---|
| apiUrl | true | false | - | The URL string of your API endpoint where the refresh token call should be made. |
| getTokens | true | true | - | An async supported function that should return a valid accessToken and refreshToken stored in the client. Because this supports aysnc, you can use local storage or async storage which requires 'await'. |
| fetchBody | true | true | - | The query required to fetch a new access token with when a valid refresh token was given. The package also accepts an optional 'variables' attribute which can contain additional fields if required by the server, such as 'email'. |
| fetchHeaders | false | false | { 'Content-Type': 'application/json' } | An optional attribute to set the headers needed during the refresh token fetch. |
| onRefreshComplete | true | true | - | The main callback required to handle the fetch logic. This function should contain the logic required to parse the tokens from the response and return the new access and refresh tokens to the utility. You can also perform any other logic in here on failures, such as calling a sign out method already defined in the application. |
| debugMode | false | false | false | Optional boolean that sends helpful console logs to the output for debugging purposes. Recommended to leave this off for production. |
const getTokens = async () => {
const accessToken = await getAsyncStorage(ACCESS_TOKEN);
const refreshToken = await getAsyncStorage(REFRESH_TOKEN);
return {
accessToken,
refreshToken,
};
};
const onRefreshComplete = async (data) => {
// Find and return the access token and refresh token from the provided fetch callback
const newAccessToken = data?.data?.token?.accessToken;
const newRefreshToken = data?.data?.token?.refreshToken;
// Handle sign out logic if the refresh token attempt failed
if (!newAccessToken || !newRefreshToken) {
console.log('Redirect back to login, because the refresh token was expired!');
signOutHandler();
return;
}
// Update tokens in AsyncStorage
await setAsyncStorage(ACCESS_TOKEN, newAccessToken);
await setAsyncStorage(REFRESH_TOKEN, newRefreshToken);
// Return the tokens back to the lib to cache for later use
return {
newAccessToken,
newRefreshToken,
};
};
/**
* Configure the body of the token refresh method
*/
const fetchBody = async () => ({
query: `mutation RefreshAccessToken($email: String!, $refreshToken: String!) {
token (email: $email, refreshToken: $refreshToken) {
accessToken
refreshToken
}
}`,
variables: {
email: await getAsyncStorage(EMAIL),
},
});
/**
* Create Apollo Link JWT
*/
const apolloLinkJWT = ApolloLinkJWT({
apiUrl: GRAPHQL_API,
getTokens,
fetchBody,
onRefreshComplete,
debugMode: true,
});
const httpLink = createHttpLink({
uri: GRAPHQL_API,
});
return new ApolloClient({
link: from([
apolloLinkJWT,
httpLink, // Add terminating link last
]),
});
FAQs
Apollo Link for JWT authorization with refresh token handling
We found that apollo-link-jwt demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Security News
Socket CEO Feross Aboukhadijeh joins 10 Minutes or Less, a podcast by Ali Rohde, to discuss the recent surge in open source supply chain attacks.

Research
/Security News
Campaign of 108 extensions harvests identities, steals sessions, and adds backdoors to browsers, all tied to the same C2 infrastructure.

Security News
OpenAI rotated macOS signing certificates after a malicious Axios package reached its CI pipeline in a broader software supply chain attack.