Skip to content

Refresh the Access token using Refresh Token

Often JWT comes with a new challenge. You have to refresh the JWT token periodically using a token, named Refresh token.

A refresh token is a special kind of token used to obtain a renewed access token. You can request new access tokens until the refresh token is on the DenyList. Applications must store refresh tokens securely because they essentially allow a user to remain authenticated forever.

React Auth Kit implements an easy approach to integrate the refresh token.

You can either use the refresh token in your application or you can leave it.


API Builder (createRefresh)

To build the refresh token API, you have to use createRefresh function. It is an identity function. It is mainly used for type checking and mobility.

Import

Import createRefresh in your app
import createRefresh from 'react-auth-kit/createRefresh';

Usage

refresh.js
const refresh = createRefresh({
  interval: 10 // The time in sec to refresh the Access token,
  refreshApiCallback: async (param) => {
    try {
      const response = await axios.post("/refresh", param, {
        headers: {'Authorization': `Bearer ${param.authToken}`}
      })
      console.log("Refreshing")
      return {
        isSuccess: true,
        newAuthToken: response.data.token,
        newAuthTokenExpireIn: 10,
        newRefreshTokenExpiresIn: 60
      }
    }
    catch(error){
      console.error(error)
      return {
        isSuccess: false
      } 
    }
  }
})

Integration with the App

To add the refresh token feature, simply add the return value of createRefresh function in the createStore in the refresh prop.

app.js
import {AuthProvider} from 'react-auth-kit'
import refresh from "./refresh";

const store = createStore({
  authName:'_auth',
  authType:'cookie',
  cookieDomain: window.location.hostname,
  cookieSecure: window.location.protocol === 'https:',
  refresh: refresh
});

function App() {
  return (
    <AuthProvider store={store}>
      <Routes/>
    </AuthProvider>
  );
}

API

createRefresh

Only use the return from createRefresh as the prop value

Using values other than the return of createRefresh will cause the application to break. So only use the return of createRefresh as the prop value.

— 🔑 —

React Auth Kit is Apache 2.0 License code