DEV Community

Cover image for How to refresh-token
Daniel Lima
Daniel Lima

Posted on

How to refresh-token

Today i'm going to show you one way to refresh your token at front-end applications.

What is a token ?

In the context of computer programming, a token is a sequence of characters that represents a single, meaningful unit of information. Tokens are often used in programming languages, where they serve as the basic building blocks of code.

And in web applications we currently Json Web Tokens ( JWT ) to pass information and do/control authentication and authorization.

Image description

Ok, why i need to refresh it ?

Refresh tokens add to the security of OAuth since they allow the authorization server to issue access tokens with a short lifetime and reduced scope, thus reducing the potential impact of access token leakage. Refresh tokens are a convenient and UX-friendly way to obtain new access tokens after the expiration of older access tokens.

One reason for using refresh tokens is that they allow the server to revoke access, although not immediately, of users. Refresh tokens provide a nice division of responsibility and abstract out a large portion of the application in a well-documented, standard-based way. Refresh tokens also allow the same access token to be used for each request without reissuing it, which can significantly improve performance.

In fact, the real "excuse" for us for using refresh tokens is to provide a better user experience. A short-lived access token improves the security of applications, but frequent re-authentication can diminish the perceived user experience of the application. Refresh tokens help balance security with usability by allowing client applications to request new access tokens after the shorter-lived access tokens expire.

How can i do it ?

We have some option to do it, but the traditional way is :

Image description

Do the authentication, wait for the token expires, and when your user hit a 401 error do the refresh token and refetch the original request.

This is a noiseless way, your user don't will be alert about that, and will just keep using the app.

But, you there is another way to do it. You actually don't need to wait the 401 error, once you already know when the access_token will expires.

So, you can avoid those requestions, and when the toke is near to expires you do the refresh token without get the 401.

In that way, you will avoid several 401 errors and keep maintaining your refresh in a silent way.

Code example

This is a example using javascript, axios instances to listen the 401 and intercept it.

import axios from 'axios';

const api = axios.create({
  baseURL: 'https://api.example.com',
});

// Add the interceptors
api.interceptors.request.use(
  (config) => {
    const accessToken = localStorage.getItem('access_token');
    if (accessToken) {
      config.headers.Authorization = `Bearer \${accessToken}`;
    }
    return config;
  },
  (error) => Promise.reject(error),
);

// Add interceptor response
api.interceptors.response.use(
  (response) => response,
  async (error) => {
    const originalRequest = error.config;


    if (error.response.status === 401 && !originalRequest._retry) {
      originalRequest._retry = true;

      const refreshToken = localStorage.getItem('refresh_token');
      if (!refreshToken) {
        // Redirecionar para a página de login
        window.location.href = '/login';
        return Promise.reject(error);
      }

      try {
        const response = await axios.post('https://auth.example.com/refresh', {
          refresh_token: refreshToken,
        });
        const accessToken = response.data.access_token;

        // Storage the token
        // If you are using next, use nookies library to persist those data in cookies.
        localStorage.setItem('access_token', accessToken);
        api.defaults.headers.common.Authorization = `Bearer \${accessToken}`;

        // Send again the original request
        return api(originalRequest);
      } catch (error) {
        window.location.href = '/login';
        return Promise.reject(error);
      }
    }

    return Promise.reject(error);
  },
);

export default api;

Enter fullscreen mode Exit fullscreen mode

Hope this post can be helpful!
For some feedback or more content, follow me on twitter or github

Top comments (3)

Collapse
 
sergeyleschev profile image
Sergey Leschev

That being said, the provided code example in JavaScript is a solid implementation utilizing axios interceptors to check for expired access tokens and automatically refreshing them. It's a reliable way to maintain token validity and provides a seamless experience for users without interruption.

Collapse
 
quangdh_ct profile image
Quang Huy

That's great,

Collapse
 
polycarpx99 profile image
Polycarpx99

Very good post