Published: September 25 2021

React + Axios - Interceptor to Set Auth Header for API Requests if User Logged In

This is a quick example of how to automatically set the HTTP Authorization header for requests sent with axios from a React app to an API when the user is authenticated.

The below code snippet is from a React Facebook Login tutorial I posted a little while ago, to see the code running in a live demo app check out React - Facebook Login Tutorial & Example.

RxJS is used in the React tutorial to store the current authenticated user state in the accountService, but RxJS isn't required if your React app uses another way to store the user's logged in state such as Redux or Recoil etc. The only requirement is that you can check if the user is logged in from the axios interceptor function below (jwtInterceptor()).

 

Axios JWT Interceptor

Path: /src/_helpers/jwt.interceptor.js

The JWT Interceptor intercepts http requests from the React app to add a JWT auth token to the HTTP Authorization header if the user is logged in and the request is to the React app's API URL (process.env.REACT_APP_API_URL).

It's implemented as an axios request interceptor, by passing a callback function to axios.interceptors.request.use() you can intercept and modify requests before they get sent to the server. For more info on axios interceptors see https://github.com/axios/axios#interceptors.

The jwtInterceptor() function is executed just before app startup to enable the axios interceptor.

import axios from 'axios';

import { accountService } from '_services';

export function jwtInterceptor() {
    axios.interceptors.request.use(request => {
        // add auth header with jwt if account is logged in and request is to the api url
        const account = accountService.accountValue;
        const isLoggedIn = account?.token;
        const isApiUrl = request.url.startsWith(process.env.REACT_APP_API_URL);

        if (isLoggedIn && isApiUrl) {
            request.headers.common.Authorization = `Bearer ${account.token}`;
        }

        return request;
    });
}
 


Need Some React Help?

Search fiverr for freelance React developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by