Handle Unauthorized Error Responses

Your React frontend should handle 401 responses from your Express server.

Below are some examples of how to handle any 401 Unauthorized errors in your React frontend returned from the Auth Middleware in your Express server.


Axios Interceptor

If you're using Axios, you can create a response interceptor to handle Unauthorized responses. The typical pattern is to automatically redirect users to your login endpoint (e.g. src/api/api-client.ts).

// api-client.ts

import axios from 'axios';

import { isUnauthorized, redirectToLogin } from '@/utils/helpers';

const apiClient = axios.create({
  baseURL: `<express-server-domain>/api`,
  headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
});

// Any HTTP 401 response should redirect the user to the Login page.
const unauthorizedAccessInterceptor = (error: unknown) => {
  if (isUnauthorized(error)) { 
    redirectToLogin();
  }
  return Promise.reject(error);
};

apiClient.interceptors.response.use(undefined, unauthorizedAccessInterceptor);

export { apiClient };




Catch Errors At API Request Code

To handle unauthorized errors with more precision, add custom error handling in your API request's catch block.

// example-component.ts

import axios from 'axios';

import { isUnauthorized, redirectToLogin } from '@/utils/helpers';

export function ExampleComponent() {
  ...
  
  const handleApiCall = () => {
    try {
      const response = await axios.get(`<your-express-server-domain>/test`);
      alert('Success!');
    } catch (err: unknown) {
      if (isUnauthorized(error)) { 
        redirectToLogin();
      } else {
        console.error('Unexpected error: ', err);
        alert('Something went wrong!');
      }
    }
  }
  
  ...
  
  return <p>Hello World!</p>;
}

Let's test if your auth middleware is protecting your session endpoint.