Axios: Promise-Based HTTP Client for Browser and Node.js
What Axios is
Axios is a JavaScript HTTP client with one API for browsers and Node.js. The README sums it up in one line, "Promise based HTTP client for the browser and node.js", and its feature list explains the rest: it makes XMLHttpRequest calls in the browser and http requests in Node.js, intercepts requests and responses, transforms request and response data, cancels requests, serializes and parses JSON, serializes objects to multipart/form-data or application/x-www-form-urlencoded, and adds client-side protection against cross-site request forgery. The credits section says the design is "heavily inspired by the $http service" in AngularJS, offered as a standalone service outside that framework.
With fetch now built into Node.js and browsers, the practical question is which Axios behaviours are worth having on top of it; the tests below look at that.
The repository axios/axios was created on 18 August 2014 and is MIT-licensed; LICENSE reads "Copyright (c) 2014-present Matt Zabriskie & Collaborators". Development happens on the v1.x branch, and a legacy 0.x line still receives releases (0.35.0 is the newest). The README links documentation at axios.rest, while package.json still lists axios-http.com as the homepage.
How it works: adapters, config merging and interceptors
Adapters
Axios separates the request pipeline from the transport. An adapter is the piece that actually sends bytes, and three are built in: xhr for browsers, http for Node.js, and fetch, added in v1.7.0. The default adapter setting is the list ['xhr', 'http', 'fetch'], and Axios picks the first one available in the current environment, so Node gets the http adapter and browsers get XHR unless code asks otherwise. A custom adapter function is also accepted. Since v1.12.0 the fetch adapter accepts a custom fetch through env; the README shows Tauri's HTTP plugin and SvelteKit's load function fetch.
Config merging
Every request is described by a config object. The README spells out the order of precedence: library defaults, then the instance's defaults, then the per-request config, with later values winning. Some options are request-only: the README states that data "is request-specific: axios does not inherit or deep-merge it from defaults".
Interceptors and transforms
Request interceptors run before the adapter and response interceptors run after it. The README documents an ordering rule that surprises people: request interceptors run last-in-first-out, response interceptors first-in-first-out. Options synchronous and runWhen tune request interceptors. Separately, transformRequest and transformResponse are arrays of functions that rewrite the body; the defaults in those arrays are what turn objects into JSON on the way out and JSON text into objects on the way back.
Key features
- Errors on non-2xx by default. The default
validateStatusisstatus >= 200 && status < 300; everything else rejects with anAxiosErrorcarryingresponse,statusand acodesuch asERR_BAD_REQUESTorERR_BAD_RESPONSE. - Automatic JSON both ways. Plain objects are serialized to JSON with the matching
Content-Type, and responses are parsed as JSON when possible. - Query-string serialization.
paramsaccepts a plain object orURLSearchParams;paramsSerializercontrols array index style, a custom encoder and a maximum nesting depth (default 100). - Cancellation and timeouts.
AbortControllersignals are supported since v0.22.0; the olderCancelTokenAPI is deprecated.timeoutis in milliseconds and defaults to 0, meaning no timeout. - Progress events.
onUploadProgressandonDownloadProgresswork in the browser and in Node.js, with rate and estimate fields. - Node-specific controls.
maxRedirects(default 21), proxies fromhttp_proxy/no_proxy, Unix sockets,maxRatebandwidth caps and experimental HTTP/2 since v1.13.0. - Security-oriented options.
sensitiveHeadersstrips named secret headers on cross-origin redirects,redactmasks config keys inAxiosError#toJSON(), andmaxContentLength/maxBodyLengthcap body sizes. - TypeScript types included.
index.d.tsandindex.d.ctsship in the package.
Getting started
The README gives install commands for npm, yarn, pnpm, bun and Deno. With npm:
$ npm install axios
ES modules can use the default export or named exports:
import axios, { isCancel, AxiosError } from 'axios';
With CommonJS the README warns that "only the default export is available":
const axios = require('axios');
console.log(axios.isCancel('something'));
For anything beyond a script, the README's instance example is the pattern to copy, because it keeps base URL, timeout and headers out of the global defaults:
const instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: { 'X-Custom-Header': 'foobar' },
});
Two defaults deserve a decision on day one. The README notes "Set a timeout in production. Without one, a stalled request can hang indefinitely." And a security notice near the top of the config reference says maxContentLength and maxBodyLength default to -1 (unlimited), so a hostile server can send a small compressed body that expands to gigabytes. Its suggested fix for untrusted servers:
axios.defaults.maxContentLength = 10 * 1024 * 1024; // 10 MB
axios.defaults.maxBodyLength = 10 * 1024 * 1024;
To use the fetch adapter for a whole client instead of per request:
const fetchAxios = axios.create({
adapter: 'fetch',
});
Hands-on: axios 1.21.1 on Node.js 22
Everything in this section was run on 18 November 2026 in a Linux cloud VM: Ubuntu 24.04.5 LTS, Linux 6.18 x86_64, 2 vCPUs, Node.js 22.23.5 and npm 10.9.9. A fresh directory ran npm init -y and npm install [email protected], and a test script started a local node:http server on 127.0.0.1 with endpoints for JSON, echo, slow responses, 404/500, malformed JSON, large bodies, a gzip bomb and redirect chains. Each call was made through the http adapter, the fetch adapter and native fetch where that made sense.
Install footprint
| Measure | Result |
|---|---|
| Packages added | 27 (axios plus 26 transitive); npm audit found 0 vulnerabilities |
| Direct dependencies resolved | follow-redirects 1.16.3, form-data 4.0.6, https-proxy-agent 5.0.1, proxy-from-env 2.1.0 |
| Install time, wall clock | about 1.5 s |
node_modules total | 3,005,027 bytes (du -sb), 4.4 MB by du -sh |
axios package alone | 2,235,438 bytes in 92 files; matches the registry's unpackedSize and fileCount |
| Browser bundles | dist/axios.min.js 77,016 bytes (26,400 gzipped); dist/esm/axios.min.js 59,020 bytes (21,320 gzipped) |
| Cold process start with axios loaded | require 91-124 ms, import 104-150 ms, versus 31-36 ms for an empty node -e (three runs each) |
npm audit signatures | Failed in this VM (Failed to download); registry metadata shows a GitHub Actions trusted-publisher release with attestations |
Module formats
| Check | Observed |
|---|---|
require('axios') | Resolves to dist/node/axios.cjs; a function; axios.default === axios is true; VERSION "1.21.1" |
import | Resolves to index.js; 18 named exports including AxiosError, AxiosHeaders, getAdapter, mergeConfig, toFormData and HttpStatusCode |
axios.defaults in Node | adapter ['xhr','http','fetch'], timeout 0, maxContentLength -1, maxBodyLength -1 |
Requests, errors and cancellation
| Scenario | Axios (http adapter) | Native fetch |
|---|---|---|
| GET JSON | data is an object; response.duration present; request headers User-Agent: axios/1.21.1, Accept: application/json, text/plain, */*, Accept-Encoding: gzip, compress, deflate, br | Needs await res.json(); sends User-Agent: node, Accept: */*, Accept-Encoding: gzip, deflate |
| POST a plain object | Body {"a":1,"b":[1,2]}, Content-Type: application/json | Body [object Object], Content-Type: text/plain;charset=UTF-8 |
| POST object with URL-encoded header | Body a=1&b%5Bc%5D=2 (object serialized automatically) | - |
| 404 response | Rejects: AxiosError, code ERR_BAD_REQUEST, message "Request failed with status code 404", error.response.status 404, error.response.data {error:"nope"}, isAxiosError true | Resolves with ok: false, status 404 |
| Timeout, 200 ms against a 1.5 s endpoint | Rejects after about 202 ms: ECONNABORTED, "timeout of 200ms exceeded"; ETIMEDOUT with transitional.clarifyTimeoutError: true | With AbortSignal.timeout(200): TimeoutError, "The operation was aborted due to timeout" |
AbortController.abort() after 100 ms | CanceledError, code ERR_CANCELED, axios.isCancel() true | AbortError, "This operation was aborted" |
| Signal already aborted | Rejects in 0.3 ms; the README says no real request is made in this case | - |
| Connection refused | code ECONNREFUSED, original error on cause | TypeError: fetch failed, detail on cause |
URL http:127.0.0.1/x | ERR_INVALID_URL: Invalid URL "http:127.0.0.1/x": missing "//" after protocol | - |
redact: ['authorization'] | error.toJSON().config.headers.Authorization is [REDACTED ****]; without it the bearer token appears in full | - |
An AbortSignal.timeout() passed to Axios as signal is reported as a cancellation (ERR_CANCELED), not a timeout, so code that branches on ECONNABORTED or ETIMEDOUT will miss it. Pick one mechanism per client.
JSON parsing and transforms
| Scenario | Result |
|---|---|
Server sends {bad json as application/json, default config | Resolves; data is the string "{bad json", no error |
Same with responseType: 'json' and silentJSONParsing: false | Rejects: SyntaxError name, code ERR_BAD_RESPONSE, response still attached |
text/plain body that happens to be JSON | Parsed into an object anyway (forcedJSONParsing); responseType: 'text' keeps it a string |
transformRequest: [fn] returning a JSON string, replacing the defaults | Server received Content-Type: application/x-www-form-urlencoded, and transformResponse: [d => d] left the response as a string |
Custom function prepended to axios.defaults.transformRequest | application/json preserved; appended response transform saw the parsed object |
The silent fallback means a broken upstream can hand a string to code that expects an object. Replacing the transform arrays instead of extending them is the other easy mistake: a string body defaults to a URL-encoded Content-Type.
baseURL, params and instances
| Input | Resulting URL or behaviour |
|---|---|
params: { q: 'a b', ids: [1, 2], nested: { x: 1 }, d: Date, skip: undefined, nil: null, sym: 'a:b,c$' } | ?q=a+b&ids%5B%5D=1&ids%5B%5D=2&nested%5Bx%5D=1&d=2026-11-18T00:00:00.000Z&sym=a:b,c$; undefined and null dropped |
paramsSerializer: { indexes: null } / { indexes: true } | ids=1&ids=2 / ids%5B0%5D=1&ids%5B1%5D=2 |
paramsSerializer: { encode: encodeURIComponent } | sym=a%3Ab%2Cc%24%20d (strict RFC 3986 form) |
baseURL: '.../api/v1/' with url: '/users' | .../api/v1/users (no double slash) |
url: '../../admin' | getUri() returns .../api/v1/../../admin, which the URL parser later resolves outside the prefix |
Global header set after axios.create() | Instances created earlier did not send it; an instance created afterwards did |
The last two rows line up with the documentation's warnings: the README states "baseURL is not a security boundary", and instance defaults are copied at creation time, so global defaults set later do not reach existing instances.
Interceptors
With two request and two response interceptors on one instance, the recorded order was req2, req1, res1, res2, the documented LIFO/FIFO split. A header set with config.headers.set() reached the server, and a response error handler that returned an object turned a 404 into a resolved call.
http adapter versus fetch adapter
| Behaviour | http adapter | fetch adapter |
|---|---|---|
response.request | ClientRequest | Request |
| Timeout error code (default transitional settings) | ECONNABORTED | ETIMEDOUT |
| Connection refused | ECONNREFUSED | ERR_NETWORK, "Network Error" |
| 3-hop redirect chain, defaults | Followed, status 200 | Followed, status 200 |
Same chain, maxRedirects: 2 | Rejects: ERR_FR_TOO_MANY_REDIRECTS | Followed all three, status 200 |
maxRedirects: 0 | 302 rejects with ERR_BAD_RESPONSE | Same; with validateStatus: s => s < 400 it resolves with status 302 and location: /json |
1 MiB body, maxContentLength 100 KiB, with and without Content-Length | Rejects: ERR_BAD_RESPONSE, "maxContentLength size of 102400 exceeded", no error.response | Same |
| Gzip bomb: 50,988 bytes on the wire, 50 MiB decompressed, no limit | Resolved with 52,428,800 bytes; process RSS grew by about 98 MB | - |
Same bomb, maxContentLength 10 MiB | Rejected after 53 ms | Rejected after 41 ms |
5,000-byte POST with maxBodyLength: 1000 | Rejects before sending: "Request body larger than maxBodyLength limit" | - |
The fetch adapter's redirect result is documented: its page says "Positive maxRedirects values do not limit the number of redirects in the fetch adapter; only 0 changes its behavior." The bomb test shows why the security notice exists: 50 KB on the wire became 50 MB in memory under default settings.
One result differed from the changelog. The v1.15.0 notes say header values containing CR or LF "now throw "Invalid character in header content"". In 1.21.1 a header value of a\r\nInjected: 1 did not throw with either adapter; the server received a single X-Bad: aInjected: 1 header and no injected header. The injection was blocked, but by stripping the characters rather than by an error.
Quick timing, single machine
500 sequential GET requests for a small JSON body against the local server, after 50 warm-up requests, repeated three times in one process. These figures describe this VM only and are dominated by per-request overhead, not network time.
| Client | Per request, three rounds |
|---|---|
| Axios, http adapter (instance) | 0.48, 0.49, 0.41 ms |
| Axios, fetch adapter (instance) | 0.79, 0.74, 0.82 ms |
Native fetch + json() | 0.59, 0.45, 0.22 ms |
Native fetch varied the most between rounds. The fetch adapter was consistently the slowest of the three here, which is worth knowing before switching a Node service to it for consistency with browser code.
How Axios compares
The table covers same-category HTTP clients. Feature descriptions come from each project's README and versions from the npm registry, both fetched on 18 November 2026; none of the alternatives were run here. Two caveats on sources: the ky README says it "is for the next version of Ky", and the ofetch README is on its v2 alpha branch while npm's latest is 1.5.1.
| Client | What its README says | Runs in | Retries built in | Latest on npm | Runtime deps (npm) | Licence |
|---|---|---|---|---|---|---|
| Axios | "Promise based HTTP client for the browser and node.js" | Browsers, Node.js; Deno and Bun smoke-tested since v1.15.0 | No (the migration guide shows a retry interceptor pattern) | 1.21.1 | 4 | MIT |
Native fetch | Platform API; the undici README says Node's built-in fetch is "powered by a bundled version of undici" | Browsers, Node.js 18+, other runtimes | No | - | 0 | - |
| ky | "tiny and elegant HTTP client based on the Fetch API"; lists retries, timeouts, hooks, progress and treating non-2xx as errors | Modern browsers, Node.js, Bun, Deno | Yes | 2.2.0 (Node >=22) | 0 | MIT |
| got | "Human-friendly and powerful HTTP request library for Node.js"; HTTP/2, pagination, RFC 7234 caching, hooks | Node.js only; ESM only | Yes, on by default | 16.2.0 (Node >=22) | 10 | MIT |
| ofetch | "A better fetch API. Works on node, browser, and workers"; throws when response.ok is false, smart JSON parsing | Node.js, browsers, workers | Yes, for listed status codes | 1.5.1 | 3 | MIT |
| undici | "An HTTP/1.1 client, written from scratch for Node.js" | Node.js | Not described in the README sections read | 8.12.4 (Node >=22.19.0) | 0 | MIT |
| superagent | "Small progressive client-side HTTP request library, and Node.js module with the same API" | Browsers, Node.js | Listed as yes in got's comparison | 10.4.2 (Node >=14.18.0) | 9 | MIT |
Axios stands out for breadth in one long-stable API: interceptors, instance defaults, automatic JSON, URL-encoded and multipart serialization, progress in Node and browsers, Node proxy and socket handling, and an ecosystem that ECOSYSTEM.md lists, from cookie jars and caching to typed clients such as zodios. ky and ofetch cover the common needs on top of fetch with fewer dependencies, and both include retries. got is the Node-only option with the most built in, though its own README now advises "You probably want Ky instead". undici is the low-level choice: its README benchmark, run by that project on Node 24.14.1 with 50 connections and pipelining, reports about 5,448 req/sec for axios against 16,851 for undici - request. That is undici's claim on its own harness, not a measurement made here.
got's own comparison table marks axios as lacking HTTP/2 and having progress events "Browser only"; the current Axios README documents experimental HTTP/2 and marks both progress callbacks "browser & node.js", so that table looks out of date.
Use cases
- Front-end API clients. One
axios.create()instance per backend, with a request interceptor for tokens and a response interceptor for 401 handling. The backend might be Express, FastAPI or Gin; Axios does not care. - Isomorphic code. Libraries and SSR apps that run the same request code in the browser and on the server, with the adapter chosen per environment or forced to
fetchwith a framework-providedfetchfunction. - Node services calling internal APIs. Where proxies from environment variables, Unix sockets (for example a Docker daemon socket), bandwidth limits or
sensitiveHeaderson redirects matter. - Test helpers. A custom
adapterfunction can stand in for the network in unit tests; browser end-to-end tests belong to tools such as Playwright, which the Axios repository itself uses for its browser test suite.
Security posture and release integrity
SECURITY.md lists both 0.x and 1.x as supported, commits to resolving and disclosing every valid advisory within 60 days, and says vulnerable versions are deprecated on npm. It explains release verification: tarballs are published from GitHub Actions with npm provenance attestations, the default since v1.6.1 on the 1.x line and v0.31.0 on 0.x, with listed exceptions (v1.13.3 and v0.29.0 to v0.30.3 have none). It suggests npm audit signatures to check:
npm audit signatures
THREATMODEL.md is unusually detailed for a library. It splits risks into runtime threats (malicious servers, redirects, prototype pollution, proxy variables) and supply-chain threats, and it states that "npm and GitHub credentials for axios maintainers have been specifically targeted by these campaigns in the past". Listed mitigations include npm 2FA, OIDC trusted publishing, hardware-backed WebAuthn and ignore-scripts=true in the repository. The v1.15.0 changelog records the switch to OIDC trusted publishing that removed a long-lived publish token. A small inconsistency: the same document describes "Three runtime deps total" in one row and "only 4 deps" in the next, and package.json lists four.
The npm registry metadata shows the deprecation policy in practice: every release from 0.1.0 to 0.21.0 (pre-releases aside) is deprecated with "Critical security vulnerability fixed in v0.21.1", and 0.27.0 and 0.27.1 are deprecated as "Formdata complete broken". The registry's time field also records versions 1.14.1 and 0.30.4, both dated 31 March 2026, which are absent from the list of installable versions, and the changelog jumps from 1.14.0 to 1.15.0 with no 1.14.1 entry. None of the files read for this page explain those two removed versions, so pin to versions that appear in the registry's version list and check lockfiles against the advisories on the GitHub repository.
Recent releases are dense with hardening, from CRLF and no_proxy SSRF fixes (1.15.0) and prototype-pollution fixes (1.15.1, 1.15.2) to sensitive-header stripping on redirects (1.18.0). The README also opens with a sponsored notice offering extended security support for Axios v0 from HeroDevs.
Limits and when not to use it
- Unsafe defaults for untrusted servers. No timeout and no response-size cap out of the box. The test above turned 50 KB into 50 MB of memory. Set
timeout,maxContentLengthandmaxBodyLengthon every instance that talks to third parties. - Browser default ignores size caps. The security guide states the XHR adapter "does not enforce
maxContentLengthormaxBodyLength"; useadapter: 'fetch'if a browser client needs them. - Adapters are not interchangeable. Error codes for timeouts and refused connections differ, and
maxRedirectsabove 0 is ignored by the fetch adapter. Test with the adapter you ship. - Lenient JSON by default. Malformed JSON quietly becomes a string, and non-JSON content types are still parsed if they look like JSON. Strict parsing needs
responseType: 'json'plussilentJSONParsing: false. - No retries, caching or pagination. These come from interceptors or third-party add-ons; ky, ofetch and got include retries.
- HTTP/2 is experimental. The README says HTTP/2 redirects are not supported, and Bun or Deno may not work with it.
- Stream uploads and redirects. The README warns to set
maxRedirects: 0when uploading streams in Node, becausefollow-redirects"buffers the entire stream in RAM". - Dependency weight on Node. 27 packages and about 3 MB; a script that only needs GET and JSON is fine with
fetch.
Release cadence and documentation notes
The registry lists 148 installable versions since the package appeared on 29 August 2014; 1.0.0 was published on 4 October 2022, and the README says Axios "follows semver since v1.0.0". In the year to 18 November 2026 there were 24 releases: 1.x minors roughly monthly from 1.14.0 (27 March) to 1.21.0 (27 October), patch releases between them, and 0.x releases from 0.30.3 to 0.35.0. The latest is 1.21.1, published on 9 November 2026. v1.21.0 still carries a breaking note: custom class instances are no longer accepted as header defaults.
A few documentation details came up while reading. The changelog dates releases by tag or preparation date rather than publish date: it lists v1.21.0 as 21 October 2026, while npm shows it published on 27 October and the GitHub release is dated 26 October. The v1.x CHANGELOG.md has no entries for 1.20.0, 1.18.1 or 1.21.1,. The README's CDN snippets pin 1.20.0, one minor behind. The npm next dist-tag still points at 1.7.0-beta.2, a 2024 beta that is itself deprecated, so axios@next is not a way to get previews. MIGRATION_GUIDE.md covers the 0.x to 1.x move.
Project activity
Checked 18 November 2026: latest release axios 1.21.1 (9 November 2026), with 0.35.0 on the legacy line (2 November 2026 on GitHub) and 1.21.0 before that (26 October 2026); MIT licence; about 109,400 stars on the axios/axios repository (109,389 at the time of writing), with about 12,100 forks and a push on the day of checking. The project is written in JavaScript, was created on 18 August 2014 and develops on the v1.x branch. Release notes are in the changelog, the security process is in SECURITY.md, and the listed homepage is axios-http.com.
Enjoying this project?
Discover more amazing open-source projects on TechLogHub. We curate the best developer tools and projects.
Repository:https://github.com/axios/axios
GitHub - axios/axios: Axios: Promise-Based HTTP Client for Browser and Node.js
Axios is the MIT-licensed promise-based HTTP client for browsers and Node.js. Version 1.21.1 tested on Node 22: errors, timeouts, adapters, size caps and a gzip...
github - axios/axios
Related Projects
Maintain Axios: Promise-Based HTTP Client for Browser and Node.js? Add the badge to your README
Show that the project is featured on TechLogHub and send readers to this write-up.
[](https://techloghub.com/open-source/axios?utm_source=techloghub_badge&utm_medium=referral&utm_campaign=readme)