Axios is a Promise-based HTTP client for the browser and Node.js. It provides a simple and consistent API for making HTTP requests with support for request and response interception, automatic request and response body transformation, cancellation, timeouts, and extensive configuration options.
npm install axiosimport axios from "axios";For CommonJS:
const axios = require("axios");Named imports:
import { Axios, AxiosError, CancelToken, AxiosHeaders } from "axios";import axios from "axios";
// Simple GET request
const response = await axios.get("https://api.example.com/users");
console.log(response.data);
// POST request with data
const newUser = await axios.post("https://api.example.com/users", {
name: "John Doe",
email: "john@example.com"
});
// Request with custom configuration
const config = {
method: "get",
url: "https://api.example.com/data",
timeout: 5000,
headers: {
"Authorization": "Bearer token123"
}
};
const result = await axios(config);Axios is built around several key components:
axios.create()Core HTTP client functionality providing all standard HTTP methods with Promise-based responses. The main axios export is a pre-configured instance ready for immediate use.
// Default axios instance - function interface
axios(config: AxiosRequestConfig): Promise<AxiosResponse>;
axios(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse>;
// HTTP method shortcuts
axios.get(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse>;
axios.post(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse>;
axios.put(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse>;
axios.patch(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse>;
axios.delete(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse>;
axios.head(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse>;
axios.options(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse>;
// Form-based methods
axios.postForm(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse>;
axios.putForm(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse>;
axios.patchForm(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse>;Create custom axios instances with their own configuration defaults, useful for different APIs or environments.
axios.create(config?: CreateAxiosDefaults): AxiosInstance;
interface CreateAxiosDefaults {
baseURL?: string;
timeout?: number;
headers?: RawAxiosRequestHeaders | AxiosHeaders;
// ... other AxiosRequestConfig properties
}Intercept requests and responses to transform data, add authentication, handle errors, or implement retry logic.
// Available on any axios instance
axios.interceptors.request.use(
onFulfilled?: (config: InternalAxiosRequestConfig) => InternalAxiosRequestConfig | Promise<InternalAxiosRequestConfig>,
onRejected?: (error: any) => any,
options?: AxiosInterceptorOptions
): number;
axios.interceptors.response.use(
onFulfilled?: (response: AxiosResponse) => AxiosResponse | Promise<AxiosResponse>,
onRejected?: (error: any) => any
): number;
interface AxiosInterceptorOptions {
synchronous?: boolean;
runWhen?: (config: InternalAxiosRequestConfig) => boolean;
}Cancel HTTP requests using tokens or AbortSignal to prevent unnecessary network usage and handle component cleanup.
// CancelToken-based cancellation
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
axios.get(url, { cancelToken: source.token });
source.cancel("Operation canceled");
// AbortSignal-based cancellation (modern approach)
const controller = new AbortController();
axios.get(url, { signal: controller.signal });
controller.abort();Structured error handling with detailed error information, error codes, and type checking utilities.
// Error checking
axios.isAxiosError(error: any): boolean;
axios.isCancel(error: any): boolean;
// Error classes
class AxiosError extends Error {
config?: InternalAxiosRequestConfig;
code?: string;
request?: any;
response?: AxiosResponse;
isAxiosError: boolean;
status?: number;
}
class CanceledError extends AxiosError {}Advanced header manipulation with type-safe operations and automatic content-type handling.
class AxiosHeaders {
constructor(headers?: RawAxiosHeaders | AxiosHeaders | string);
set(headerName: string, value: AxiosHeaderValue, rewrite?: boolean): AxiosHeaders;
get(headerName: string, parser?: RegExp): RegExpExecArray | null;
has(header: string, matcher?: AxiosHeaderMatcher): boolean;
delete(header: string | string[], matcher?: AxiosHeaderMatcher): boolean;
// Specialized methods
setContentType(value: ContentType, rewrite?: boolean): AxiosHeaders;
setAuthorization(value: AxiosHeaderValue, rewrite?: boolean): AxiosHeaders;
}Convert between different data formats including FormData, JSON, and URL-encoded data with extensive serialization options.
// Form data conversion
axios.toFormData(sourceObj: object, targetFormData?: GenericFormData, options?: FormSerializerOptions): GenericFormData;
axios.formToJSON(form: GenericFormData | GenericHTMLFormElement): object;
// Configuration merging
axios.mergeConfig(config1: AxiosRequestConfig, config2: AxiosRequestConfig): AxiosRequestConfig;
// Adapter selection
axios.getAdapter(adapters: AxiosAdapterConfig | AxiosAdapterConfig[]): AxiosAdapter;Helper functions for common operations and compatibility with Promise patterns.
/**
* Spread array of responses into separate arguments (Promise.all helper)
* @param callback - Function to call with spread arguments
* @returns Function that takes array and spreads it to callback
*/
axios.spread<T, R>(callback: (...args: T[]) => R): (array: T[]) => R;
/**
* Execute multiple requests concurrently (wrapper for Promise.all)
* @param promises - Array of axios request promises
* @returns Promise resolving to array of responses
*/
axios.all<T>(promises: Array<T | Promise<T>>): Promise<T[]>;Usage Examples:
import axios from "axios";
// Using spread to handle multiple concurrent requests
function getUserData(userIds) {
const requests = userIds.map(id => axios.get(`/users/${id}`));
return axios.all(requests)
.then(axios.spread((user1, user2, user3) => {
// Each parameter is a response object
console.log("User 1:", user1.data);
console.log("User 2:", user2.data);
console.log("User 3:", user3.data);
return [user1.data, user2.data, user3.data];
}));
}
// Modern async/await alternative
async function getUserDataModern(userIds) {
const requests = userIds.map(id => axios.get(`/users/${id}`));
const responses = await axios.all(requests);
return responses.map(response => response.data);
}Access to the current axios library version.
/**
* Current axios library version string
*/
axios.VERSION: string;Usage Examples:
console.log("Using axios version:", axios.VERSION); // "1.11.0"
// Useful for debugging or feature detection
if (axios.VERSION >= "1.0.0") {
// Use modern axios features
}Comprehensive enum of HTTP status codes with both numeric and named access.
enum HttpStatusCode {
// 1xx Informational
Continue = 100,
SwitchingProtocols = 101,
Processing = 102,
EarlyHints = 103,
// 2xx Success
Ok = 200,
Created = 201,
Accepted = 202,
NoContent = 204,
PartialContent = 206,
// 3xx Redirection
MultipleChoices = 300,
MovedPermanently = 301,
Found = 302,
SeeOther = 303,
NotModified = 304,
TemporaryRedirect = 307,
PermanentRedirect = 308,
// 4xx Client Error
BadRequest = 400,
Unauthorized = 401,
Forbidden = 403,
NotFound = 404,
MethodNotAllowed = 405,
RequestTimeout = 408,
Conflict = 409,
Gone = 410,
PreconditionFailed = 412,
PayloadTooLarge = 413,
UnsupportedMediaType = 415,
ImATeapot = 418,
UnprocessableEntity = 422,
TooManyRequests = 429,
// 5xx Server Error
InternalServerError = 500,
NotImplemented = 501,
BadGateway = 502,
ServiceUnavailable = 503,
GatewayTimeout = 504
// ... includes all standard HTTP status codes
}Usage Examples:
import axios, { HttpStatusCode } from "axios";
try {
const response = await axios.get("/api/data");
if (response.status === HttpStatusCode.Ok) {
console.log("Success:", response.data);
}
} catch (error) {
if (error.response?.status === HttpStatusCode.NotFound) {
console.log("Resource not found");
} else if (error.response?.status === HttpStatusCode.Unauthorized) {
console.log("Authentication required");
} else if (error.response?.status >= HttpStatusCode.InternalServerError) {
console.log("Server error occurred");
}
}
// Use in status validation
const api = axios.create({
validateStatus: (status) => status < HttpStatusCode.InternalServerError
});interface AxiosRequestConfig<D = any> {
// Core request settings
url?: string;
method?: Method;
baseURL?: string;
data?: D;
params?: any;
// Headers and authentication
headers?: RawAxiosRequestHeaders | AxiosHeaders;
auth?: AxiosBasicCredentials;
withCredentials?: boolean;
// Data transformation
transformRequest?: AxiosRequestTransformer | AxiosRequestTransformer[];
transformResponse?: AxiosResponseTransformer | AxiosResponseTransformer[];
paramsSerializer?: ParamsSerializerOptions | CustomParamsSerializer;
// Response handling
responseType?: ResponseType;
responseEncoding?: responseEncoding;
timeout?: number;
timeoutErrorMessage?: string;
validateStatus?: (status: number) => boolean;
// Progress tracking
onUploadProgress?: (progressEvent: AxiosProgressEvent) => void;
onDownloadProgress?: (progressEvent: AxiosProgressEvent) => void;
// Request/Response size limits
maxContentLength?: number;
maxBodyLength?: number;
maxRedirects?: number;
maxRate?: number;
// Networking
proxy?: AxiosProxyConfig | false;
httpAgent?: any;
httpsAgent?: any;
socketPath?: string | null;
// Security
xsrfCookieName?: string;
xsrfHeaderName?: string;
withXSRFToken?: boolean | ((config: InternalAxiosRequestConfig) => boolean | Promise<boolean>);
// Cancellation
cancelToken?: CancelToken;
signal?: GenericAbortSignal;
// Advanced options
adapter?: AxiosAdapterConfig | AxiosAdapterConfig[];
decompress?: boolean;
transitional?: TransitionalOptions;
insecureHTTPParser?: boolean;
env?: { FormData?: new (...args: any[]) => object };
formSerializer?: FormSerializerOptions;
// Node.js specific
lookup?: LookupAddress | LookupAddressEntry[];
family?: AddressFamily | undefined;
// Browser specific
fetchOptions?: Record<string, any>;
}
interface AxiosResponse<T = any> {
data: T;
status: number;
statusText: string;
headers: RawAxiosResponseHeaders | AxiosResponseHeaders;
config: InternalAxiosRequestConfig;
request?: any;
}
type Method = 'get' | 'GET' | 'delete' | 'DELETE' | 'head' | 'HEAD' | 'options' | 'OPTIONS'
| 'post' | 'POST' | 'put' | 'PUT' | 'patch' | 'PATCH';
type ResponseType = 'arraybuffer' | 'blob' | 'document' | 'json' | 'text' | 'stream' | 'formdata';
interface AxiosProgressEvent {
loaded: number;
total?: number;
progress?: number;
bytes: number;
rate?: number;
estimated?: number;
upload?: boolean;
download?: boolean;
event?: BrowserProgressEvent;
lengthComputable: boolean;
}
interface TransitionalOptions {
silentJSONParsing?: boolean;
forcedJSONParsing?: boolean;
clarifyTimeoutError?: boolean;
}
interface AxiosBasicCredentials {
username: string;
password: string;
}
interface AxiosProxyConfig {
host: string;
port: number;
auth?: AxiosBasicCredentials;
protocol?: string;
}
interface ParamsSerializerOptions {
dots?: boolean;
indexes?: boolean | null;
encode?: (value: any, defaultEncoder: (value: any) => any) => any;
serialize?: (params: Record<string, any>, options?: ParamsSerializerOptions) => string;
}