Acquiring a new token with `axios.interceptors`

This is what I did before. Your configuration is a little different from mine.

const baseURL = localStorage.getItem('domain');
const defaultOptions = {
  baseURL,
  method: 'get',
  headers: {
    'Content-Type': 'application/json',
  }
};
// Create Instance
const axiosInstance = axios.create(defaultOptions);
// Get token from session
const accessToken = ...

// Set the auth token for any request
instance.interceptors.request.use(config => {
  config.headers.Authorization = accessToken ? `Bearer ${accessToken}` : '';
  return config;
});

// Last step: handle request error general case
instance.interceptors.response.use(
  response => response,
  error => {
    // Error
    const { config, response: { status } } = error;

    if (status === 401) {
      // Unauthorized request: maybe access token has expired!
      return refreshAccessToken(config);
    } else {
      return Promise.reject(error);
    }
  }
});

I think this part should be separated with Components - it will be placed on helpers or utils. Also, you have to wait for 24 hrs because refreshToken() method is never called before 24 hrs. You don't need to process client_id, secret_id, grant_type right here.


Please check if I have correctly configured axios.interceptors.

I think it works. But I suggest that you should test it carefully.This is a good article to refer https://blog.liplex.de/axios-interceptor-to-refresh-jwt-token-after-expiration/

Have I placed it in the right place, i.e. above theItems class. ?

You should create a service function to wrap Axios and API configs,and interceptor of course

axios.interceptors.response is assigned to the interceptor variable. What should I do with this variable?

It is just a variable used to define the interceptor. Don't care about it. If you want to avoid assigning it, just do it inside a function like this Automating access token refreshing via interceptors in axios

I have to wait 24 hours to test whether it works, or is it possible in a different way, faster?

You can change the token saved in your localStorage, and do that

Where should I put 'client_id', 'secret_id', 'grant_type'?

If you store it inside localStorage, it's accessible by any script inside your page (which is as bad as it sounds as an XSS attack can let an external attacker get access to the token).

Don't store it in local storage (or session storage). If any of the 3rd part scripts you include in your page gets compromised, it can access all your users' tokens.

The JWT needs to be stored inside an HttpOnly cookie, a special kind of cookie that's only sent in HTTP requests to the server, and it's never accessible (both for reading or writing) from JavaScript running in the browser.