Skip to content

Axios add a custom header to all HTTP request in React

Last updated on July 10, 2023

To add a custom header to all HTTPS requests in a React.js application using Axios, you can set up an Axios instance with default headers. Here’s an example:

Install Axios using npm:

npm install axios

Create a new file, e.g., axiosInstance.js, and configure the Axios instance with default headers:

import axios from 'axios';

const axiosInstance = axios.create({
  baseURL: 'https://api.example.com', // Replace with your API base URL
  headers: {
    'Content-Type': 'application/json',
    'Custom-Header': 'Custom Value',
  },
});

export default axiosInstance;

In this example, the Axios instance is configured with the base URL and default headers. You can modify the headers according to your requirements.

Use the Axios instance in your React components to make HTTP requests:

import React, { useEffect } from 'react';
import axiosInstance from './axiosInstance';

function MyComponent() {
  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await axiosInstance.get('/data');
        console.log(response.data); // Output the response data
      } catch (error) {
        console.error('Error:', error.response.data);
      }
    };

    fetchData();
  }, []);

  return (
    <div>
      {/* Your component JSX */}
    </div>
  );
}

export default MyComponent;

In this example, the Axios instance (axiosInstance) is used to make a GET request to '/data'. The default headers configured in the Axios instance will be automatically included in this request.

By setting up an Axios instance with default headers, you can reuse the same configuration across your React components and ensure that the custom header is added to all HTTPS requests made using Axios.

Remember to handle any errors that may occur during the HTTP requests and handle the response appropriately based on your application’s requirements.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments