Socket
Socket
Sign inDemoInstall

apollo-link-oauth-token-refresh

Package Overview
Dependencies
37
Maintainers
1
Versions
6
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    apollo-link-oauth-token-refresh

Apollo Link that performs OAuth access tokens renewal


Version published
Weekly downloads
75
decreased by-1.32%
Maintainers
1
Created
Weekly downloads
 

Readme

Source

Purpose

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

Installation

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

Usage

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,
});

Options

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

namevalueexplanation
accessTokenField?stringDefault: 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[]) => booleanIndicates 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 => anyUsed to handle the response status & extract your token
handleError?(err: Error) => voidToken fetch error callback. Allows to run additional actions like logout. Don't forget to handle Error if you are using this option

Example

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');
        user.logout();
      } 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');
       console.error(err);

       // your custom action here
       user.logout();
    }
  }),
  errorLink,
  requestLink,
  ...
])

Context

The Token Refresh Link does not use the context for anything

Keywords

FAQs

Last updated on 16 Aug 2021

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.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc