Apollo Link that performs OAuth access tokens renewal

Usage no npm install needed!

<script type="module">
  import apolloLinkOauthTokenRefresh from 'https://cdn.skypack.dev/apollo-link-oauth-token-refresh';


Apollo OAuth Token Refresh Link npm version


An Apollo Link that performs OAuth access token renewal when the token is expired


npm install apollo-link-oauth-token-refresh --save


Token Refresh Link is non-terminating link, which means that this link shouldn't be the last link in the composed chain.

import { TokenRefreshLink } from "apollo-link-oauth-token-refresh";

const link = new TokenRefreshLink({
  isTokenValidOrUndefined: () => boolean,
  fetchAccessToken: () => Promise<Response>,
  handleResponse: (operation) => response,
  handleError?: (err: Error) => void,


Token Refresh Link takes an object with four options on it to customize the behavior of the link

name value explanation
accessTokenField? string Default: access_token. This is a name of access token field in response. In some scenarios we want to pass additional payload with access token, i.e. new refresh token, so this field could be the object's name
isTokenValidOrUndefined (...args: any[]) => boolean Indicates the current state of access token expiration. If the token is not yet expired or the user does not require a token (guest), then true should be returned
fetchAccessToken (...args: any[]) => Promise<Response> Function covers fetch call with request fresh access token
handleResponse (operation) => response => any Used to handle the response status & extract your token
handleError? (err: Error) => void Token fetch error callback. Allows to run additional actions like logout. Don't forget to handle Error if you are using this option


import { TokenRefreshLink } from 'apollo-link-oauth-token-refresh';

link: ApolloLink.from([
  new TokenRefreshLink({
    isTokenValidOrUndefined: () => !isTokenExpired() || typeof getAccessToken() !== 'string',
    fetchAccessToken: () => {
      return fetch(getEndpoint('getAccessTokenPath'), {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        body: `grant_type=refresh_token&client_id=${getOauthClientId()}&client_secret=${getOauthClientSecret()}&refresh_token=${getRefreshToken()}`
    handleResponse: () => (response) => {
      // here you can handle response & save the token
      if (response.status === 401) {
        console.warn('token has been revoked');
      } else {
        return response.json().then(data => saveToken(data));
    handleError: err => {
       // full control over handling token fetch Error
       console.warn('Your refresh token is invalid. Try to relogin');

       // your custom action here


The Token Refresh Link does not use the context for anything