2
0
mirror of https://github.com/tenrok/axios.git synced 2026-06-17 19:21:29 +03:00

fix(fetch-adapter): set User-Agent header to match http adapter (#10772)

The fetch adapter was not setting a User-Agent header, causing requests
to use Node.js's default 'node' user agent instead of 'axios/<version>'.
This mirrors the existing behavior in the HTTP adapter.

Fixes #7494

Co-authored-by: Ofek Danny <ofek@kaps.co.il>
Co-authored-by: Jay <jasonsaayman@gmail.com>
This commit is contained in:
Ofek Danny
2026-04-26 13:37:24 +03:00
committed by GitHub
parent 694f1eca8c
commit c918e85e91
2 changed files with 51 additions and 0 deletions
+4
View File
@@ -12,6 +12,7 @@ import {
import resolveConfig from '../helpers/resolveConfig.js';
import settle from '../core/settle.js';
import estimateDataURLDecodedBytes from '../helpers/estimateDataURLDecodedBytes.js';
import { VERSION } from '../env/data.js';
const DEFAULT_CHUNK_SIZE = 64 * 1024;
@@ -277,6 +278,9 @@ const factory = (env) => {
}
}
// Set User-Agent header if not already set (fetch defaults to 'node' in Node.js)
headers.set('User-Agent', 'axios/' + VERSION, false);
const resolvedOptions = {
...fetchOptions,
signal: composedSignal,
+47
View File
@@ -14,6 +14,7 @@ import stream from 'stream';
import { AbortController } from 'abortcontroller-polyfill/dist/cjs-ponyfill.js';
import util from 'util';
import NodeFormData from 'form-data';
import { VERSION } from '../../../lib/env/data.js';
const SERVER_PORT = 8010;
const LOCAL_SERVER_URL = `http://localhost:${SERVER_PORT}`;
@@ -619,6 +620,52 @@ describe.runIf(typeof fetch === 'function')('supports fetch with nodejs', () =>
});
});
describe('fetch adapter - User-Agent header', () => {
it('should set User-Agent header to axios/<version> by default', async () => {
const server = await startHTTPServer(
(req, res) => {
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ userAgent: req.headers['user-agent'] }));
},
{ port: SERVER_PORT }
);
try {
const { data } = await fetchAxios.post(`http://localhost:${server.address().port}/`, {
payload: 'test',
});
assert.strictEqual(data.userAgent, `axios/${VERSION}`);
} finally {
await stopHTTPServer(server);
}
});
it('should not override a user-provided User-Agent header', async () => {
const customUA = 'my-custom-agent/1.0';
const server = await startHTTPServer(
(req, res) => {
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ userAgent: req.headers['user-agent'] }));
},
{ port: SERVER_PORT }
);
try {
const { data } = await fetchAxios.post(
`http://localhost:${server.address().port}/`,
{ payload: 'test' },
{ headers: { 'User-Agent': customUA } }
);
assert.strictEqual(data.userAgent, customUA);
} finally {
await stopHTTPServer(server);
}
});
});
describe('env config', () => {
it('should respect env fetch API configuration', async () => {
const { data, headers } = await fetchAxios.get('/', {