How to Set HTTP Headers with Axios (With Examples)
TutorialsLearn how to set HTTP headers with Axios, including GET and POST requests, using custom headers, default headers, and axios instances.

Eugenijus Denisov
Key Takeaways
-
Use default headers to apply standard settings like the authorization header across all Axios requests.
-
Apply custom headers when your HTTP request needs something unique, like file upload or session data.
-
Use an Axios instance to organize and reuse configured headers for multiple HTTP(S) requests.
Axios is a promise-based HTTP client for JavaScript. It helps you send HTTP requests and handle responses easily. The client makes the process simple and clean when working with GET, POST, and HTTP requests.
Setting Axios headers correctly is key when you’re dealing with APIs. They help with things like passing tokens for authentication, telling the server what kind of data you’re sending, or managing cross-origin rules (CORS). Without proper request headers, many HTTP requests can fail or behave unexpectedly.
What Are HTTP Headers in Axios
HTTP headers are key-value pairs sent along with a request or a response. They give the server or client extra information. When making HTTP requests, these headers help define the context: what kind of data is being sent, who’s sending it, and how it should be processed.
In Axios, you use the headers object to include these key-value pairs. It’s part of the configuration for your Axios requests.
Axios allows default headers to be applied globally. It means you can set something like an authorization header once, and it gets used for every HTTP request. You can also use custom headers on specific calls when needed.
Setting Headers for GET and POST Requests
When sending requests using Axios headers, you can include custom headers easily by passing a headers object as part of the config. It’s helpful for things like sending an authorization header, changing the Content-Type, or setting other dynamic headers.
Axios GET Request With Custom Headers
const axios = require('axios');
axios.get('https://httpbin.org/headers', {
headers: {
'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
'X-Custom-Header': 'CustomValue'
}
})
.then(response => {
console.log(JSON.stringify(response.data, null, 2));
})
.catch(error => {
console.error('Error:', error.message);
});
Assuming Axios is installed, it’ll add both the authorization header and a custom header to the request. These request headers help the server identify who you are and process the HTTP request properly.
You can also add dynamic headers based on variables:
const axios = require('axios');
const token = getUserToken();
axios.get('https://httpbin.org/headers', {
headers: {
'Authorization': `Bearer ${token}`,
'X-Custom-Header': 'CustomValue'
}
})
.then(response => {
console.log(JSON.stringify(response.data, null, 2));
})
.catch(error => {
console.error('Error:', error.message);
});
It’s a clean way to include authentication data in requests, especially when using HTTPS for secure transmission.
Axios POST Request With Headers
A POST often needs headers to describe the request data. Here’s how to use Axios POST headers:
const axios = require('axios');
const token = getUserToken();
axios.post('https://httpbin.org/post',
{
name: 'Jane',
role: 'admin'
},
{
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
}
}
)
.then(response => {
console.log(JSON.stringify(response.data, null, 2));
})
.catch(error => {
console.error('Error:', error.message);
});
These POST Axios headers include both a Content-Type header to specify JSON data and an Authorization header to pass an access token securely.
If you want to send a file, you’ll need a different headers object:
const axios = require('axios');
const token = getUserToken();
const formData = new FormData();
formData.append('file', fileInput.files[0]);
axios.post('https://httpbin.org/post', formData, {
headers: {
'Content-Type': 'multipart/form-data',
'Authorization': `Bearer ${token}`
}
})
.then(response => {
console.log(JSON.stringify(response.data, null, 2));
})
.catch(error => {
console.error('Error:', error.message);
});
You’re telling the server to expect file data. Make sure you configure headers correctly, or the request may not work.
Using Axios Instances for Header Management
An Axios instance is a custom version of Axios that you can configure once and reuse throughout your app. Instead of repeating the same headers object or base URL in every single HTTP request, you set them up once inside the instance.
It helps when you’re making lots of HTTP(S) requests to the same API or when you need shared default headers, like an authorization header, across different parts of your code.
You should use an Axios instance when:
- You’re calling the same base URL many times.
- You want to apply default headers globally.
- You need a consistent config, such as with timeouts or custom headers.
Here’s how to create an instance with axios.create():
const axios = require('axios');
const apiClient = axios.create({
baseURL: 'https://httpbin.org',
headers: {
'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
'Content-Type': 'application/json'
}
});
apiClient.get('/headers')
.then(response => {
console.log(JSON.stringify(response.data, null, 2));
})
.catch(error => {
console.error('Error:', error.message);
});
It now includes default headers for every HTTP request. You don’t have to configure headers each time you use it manually.
Here’s how you’d use it:
apiClient.get('/profile');
apiClient.post('/update', { name: 'John' });
Both of these requests automatically use the same headers object defined in the instance. You can also add dynamic headers later if needed:
apiClient.defaults.headers['X-Session-ID'] = getSessionId();
It makes the Axios instance perfect for managing request headers across multiple POST calls, GET requests, or HTTP requests in loops.
Common Header Use Cases
You’ll often need to set headers for tasks like authenticating API requests or uploading files. Axios makes it easy to manage these using the headers object, default headers, or even dynamic headers that change with each user session.
Setting Authorization Tokens
When working with secure APIs, you’ll almost always need to send an authorization token, which is passed in the authorization header, letting the server know who you are.
You can set it for one HTTP request like this:
const axios = require('axios');
const token = getUserToken();
axios.get('https://httpbin.org/headers', {
headers: {
'Authorization': `Bearer ${token}`
}
})
.then(response => {
console.log(JSON.stringify(response.data, null, 2));
})
.catch(error => {
console.error('Error:', error.message);
});
Or, you can set it globally using default headers, which helps with multiple Axios requests:
axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
That way, every request includes the authorization header automatically. It’s also a good idea to use dynamic headers if tokens change after login.
Setting Content-Type Headers
The Content-Type header tells the server what kind of request data you’re sending. For JSON APIs, it’s usually:
headers: {
'Content-Type': 'application/json'
}
But if you’re uploading files or sending forms, you may sometimes need to change it to multipart/form-data. You usually don’t need to define it manually since Axios automatically sets the correct multipart/form-data header when sending FormData, but keep it in mind just in case.
Here’s an example using a POST request with a file:
const formData = new FormData();
formData.append('avatar', fileInput.files[0]);
axios.post('https://httpbin.org/post', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
});
The Axios POST headers in this example help the server correctly read the file data. You can also use Axios instance defaults if you always send a specific format.
Authentication and Session Headers
Some systems use different authentication headers, not just tokens. For example, API keys or session IDs:
headers: {
'x-api-key': 'my_api_key_123',
'x-session-id': 'ABC123XYZ'
}
These custom headers let you pass extra data that the server expects. You can add them to individual requests or set them as custom default headers if needed across your app.
Conclusion
Setting up Axios headers the right way makes your code more reliable, secure, and easier to manage. Axios gives you the tools to handle everything: default headers that apply globally, custom headers that you can tweak per call, and more.
Using an Axios instance helps you keep HTTP(S) requests consistent, while dynamic headers give you flexibility for sessions and user tokens. If you need more flexibility and performance, you may also want to consider using Axios with proxies .