React: how to add a Bearer Token to all HTTP requests

React: how to add a Bearer Token to all HTTP requests

In this article, we will explore how to add a Bearer Token to all HTTP requests in a React application.

React is a widely used JavaScript library for building dynamic and responsive user interfaces. When developing a web application with React that interfaces with a secure API server, it is often necessary to authenticate HTTP requests using a Bearer access token. In this article, we will explore how to add a Bearer Token to all HTTP requests in a React application.

Getting the Bearer Token

First of all, you need to obtain a Bearer access token from your server's authentication endpoint. This is usually done through a login process, where the user's credentials are sent to the server and, if valid, an access token is returned.


// Example of access request and obtaining token
fetch('https://api.example.com/login', {
   method: 'POST',
   headers: {
     'Content-Type': 'application/json',
   },
   body: JSON.stringify({
     username: 'yourUsername',
     password: 'yourPassword',
   }),
})
   .then(response => response.json())
   .then(data => {
     const accessToken = data.accessToken;
     // Save the access token in a React state or state management system
   })
   .catch(error => console.error('Error logging in:', error));

Create a Wrapper for HTTP Requests

Once we have the access token, we can create a wrapper for HTTP requests that automatically includes the token in every request. We can do this by using the request interceptor of a library for HTTP calls, such as Axios.


// Wrapper for HTTP requests with Axios
import axios from 'axios';

const api = axios.create({
   baseURL: 'https://api.example.com',
});

// Add an interceptor for all requests
api.interceptors.request.use(config => {
   // Retrieve the access token from React state or a state management system
   const accessToken = 'yourAccessToken';

   // Add the access token to the Authorization header
   config.headers.Authorization = `Bearer ${accessToken}`;

   return config;
});

export default api;

Using the Wrapper in API Calls

Now that we have created the wrapper for HTTP requests, we can use it in our API calls.


// Example of using the wrapper for HTTP requests
import api from './api'; // Import the wrapper

// Make a GET request
api.get('/data')
   .then(response => {
     // Handle the response
     console.log(response.data);
   })
   .catch(error => {
     // Handle errors
     console.error('Error in request:', error);
   });

With this approach, every HTTP request made with the Axios wrapper will automatically include the Bearer access token in the Authorization header. This simplifies the management of authentication in your React applications, ensuring that every request to the server is authorized correctly.