Set Custom Referer Headers in Axios Node.js
Setting a custom Referer header in Axios within a
server-side Node.js environment allows you to mimic traffic from
specific web pages, fulfill third-party API requirements, or manage
internal tracking. This guide covers how to set the Referer
header on individual requests, configure it globally using Axios
instances, and understand the differences between browser and
server-side header behavior.
Setting the Referer Header on a Single Request
To pass a Referer header in a single Axios call, include
a headers object inside the request configuration.
const axios = require('axios');
async function fetchData() {
try {
const response = await axios.get('https://api.example.com/data', {
headers: {
'Referer': 'https://mycustomsite.com/dashboard'
}
});
console.log(response.data);
} catch (error) {
console.error('Request failed:', error.message);
}
}
fetchData();For POST, PUT, or PATCH requests, the configuration object is passed as the third argument:
await axios.post(
'https://api.example.com/submit',
{ key: 'value' },
{
headers: {
'Referer': 'https://mycustomsite.com/form'
}
}
);Setting the Referer Header Across an Axios Instance
If multiple requests require the same custom referer, create an Axios instance with pre-configured default headers:
const axios = require('axios');
const apiClient = axios.create({
baseURL: 'https://api.example.com',
headers: {
'Referer': 'https://mycustomsite.com'
}
});
// All requests made with apiClient will include the Referer header
async function run() {
const response1 = await apiClient.get('/endpoint-one');
const response2 = await apiClient.get('/endpoint-two');
}You can also set the header globally on the default Axios object:
axios.defaults.headers.common['Referer'] = 'https://mycustomsite.com';Server-Side vs. Browser Restrictions
In browser environments, the Referer header is
classified as a forbidden header name and cannot be modified
programmatically via JavaScript for security reasons.
In a Node.js server environment, these browser-based security
restrictions do not apply. Node.js allows full control over HTTP
headers, meaning you can set any valid URL string as the
Referer value without receiving a security error or having
the value stripped by the runtime.