Handle Unauthorized Error Responses

Update your frontend to handle Unauthorized responses from your backend server.

Patterns For Handling Unauthorized Errors

Below are some common patterns for handling 401 Unauthorized errors in your React frontend.


Use an Axios Interceptor

If you're using Axios, you can create a response interceptor to handle Unauthorized responses. In the example below, the user is redirected to the Login Endpoint if a 401 response is detected.

// api-client.ts

import axios from 'axios';

const apiClient = axios.create({
  baseURL: '<Replace with the base URL of your server APIs>',
  headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
});

// If a 401 response is detected, redirect the user to your Login Endpoint.
const unauthorizedAccessInterceptor = (error: unknown) => {
  if (axios.isAxiosError(error) && error.response?.status === 401) {
    window.location.href = '<Replace with your application Login Endpoint>';
    return;
  }
  return Promise.reject(error);
};

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

export { apiClient };




Explicitly Catch Errors When Making API Calls

To handle unauthorized errors with more precision, you can explicitly catch errors thrown when calling your backend APIs. This allows for custom error-handling logic to be created for each API call.

// example-component.ts

import axios from 'axios';

export function ExampleComponent() {
  ...
  
  const executeServerApiCall = async () => {
    try {
      const response = await axios.get('<your-server-api-url>');
      alert('Success!');
    } catch (error: unknown) {
      if (axios.isAxiosError(error) && error.response?.status === 401) { 
        window.location.href = '<Replace with your application Login Endpoint>';
      } else {
        console.error('Unexpected error: ', error);
        alert('Something went wrong!');
      }
    }
  }
  
  ...
  
  return <p>Hello World!</p>;
}

What’s Next

Next let's confirm that your auth middleware is protecting your session endpoint.