React Best Practices

Logout on 401 Response

Use Axios interceptors

Axios lets us intercept request and response, former is used when we want to add additional configuration (headers, data etc) while the latter is used when we want to perform some action or modify the response (log errors, logout on 401 etc).

Intercept all requests

Here, we will intercept and add auth headers to all requests that will be made using Axios instance.

1const requestHandler = request => {
2  request.headers['Authorization'] = getAuthHeader();
3
4  return request;
5}
6
7axios.interceptors.request.use(request => requestHandler(request));

Listen to all responses

The request will be resolved by default when the status code is between 200 - 300, otherwise the request will be rejected. This could be changed using validateStatus in the request config.

1. Log all errors

1const responseSuccessHandler = response => {
2  return response;
3};
4
5const responseErrorHandler = error => {
6  if (error.response) {
7    console.error(error.response.data);
8    console.error(error.response.status);
9    console.error(error.response.headers);
10  } else if (error.request) {
11    console.error(error.request);
12  } else {
13    console.error('Error', error.message);
14  }
15  console.error(error.config);
16
17  return Promise.reject(error);
18}
19
20axios.interceptors.response.use(
21  response => responseSuccessHandler(response),
22  error => responseErrorHandler(error)
23);

2. Logout on 401

If status code is 401, redirect user to Login route. If we keep client side authentication states, reset them.

1const responseSuccessHandler = response => {
2  return response;
3};
4
5const responseErrorHandler = error => {
6  if (error.response.status === 401) {
7    // Add your logic to
8    //  1. Redirect user to LOGIN
9    //  2. Reset authentication from localstorage/sessionstorage
10  }
11
12  return Promise.reject(error);
13}
14
15axios.interceptors.response.use(
16  response => responseSuccessHandler(response),
17  error => responseErrorHandler(error)
18);