Set Custom User-Agent in Axios Backend Requests
Setting a custom User-Agent header in Axios backend
requests allows your Node.js application to identify itself properly to
external APIs, avoid automated bot blocking, and comply with target
server requirements. This guide demonstrates how to configure custom
User-Agent strings globally, per Axios instance, and on
individual HTTP requests.
Method 1: Setting User-Agent on a Single Request
To pass a custom User-Agent for an isolated request,
include the headers object inside the request configuration
parameter.
const axios = require('axios');
async function makeRequest() {
try {
const response = await axios.get('https://api.example.com/data', {
headers: {
'User-Agent': 'MyCustomBackendApp/1.0.0 (Node.js/18.x; +https://mywebsite.com/bot)'
}
});
console.log(response.data);
} catch (error) {
console.error('Request failed:', error.message);
}
}
makeRequest();Method 2: Setting User-Agent on an Axios Instance
Creating a dedicated Axios instance is the best practice when making multiple calls to the same service. This ensures every request sent through that instance automatically inherits the custom header.
const axios = require('axios');
const apiClient = axios.create({
baseURL: 'https://api.example.com',
timeout: 5000,
headers: {
'User-Agent': 'MyCustomBackendService/2.1.0'
}
});
// All requests using apiClient will include the User-Agent
async function fetchUser(userId) {
const response = await apiClient.get(`/users/${userId}`);
return response.data;
}Method 3: Setting User-Agent Globally
If you want every request made via the default axios
import across your backend project to share the same
User-Agent, modify
axios.defaults.headers.common.
const axios = require('axios');
// Set the global header
axios.defaults.headers.common['User-Agent'] = 'GlobalAppService/1.0.0';
// This request will automatically include the global User-Agent
async function checkStatus() {
const response = await axios.get('https://api.example.com/status');
console.log(response.data);
}Important Considerations
- Server-Side Only: The
User-Agentheader can be freely overridden in backend environments (Node.js). In browser environments, modern browsers restrict modifying this header for security reasons. - Header Capitalization: HTTP headers are
case-insensitive, but using
'User-Agent'or'user-agent'consistently helps maintain code clarity. - Standard Format: A standard
User-Agentfollows theAppName/Version (Environment; Context)structure, making it easier for API providers to contact or identify your integration.