
Security News
Attackers Are Hunting High-Impact Node.js Maintainers in a Coordinated Social Engineering Campaign
Multiple high-impact npm maintainers confirm they have been targeted in the same social engineering campaign that compromised Axios.
@axios-extensions/plugins-api
Advanced tools
Solves the missing priority / add / remove interceptors in Axios
Axios Extensions elevates your experience with Axios, offering a meticulously curated suite of extensions that enhance the capabilities of the popular HTTP client. Designed with modularity at its core, these extensions can be seamlessly integrated individually or in combination, depending on your project's needs.
Built with TypeScript, this project not only enriches your applications with additional functionality but also ensures a type-safe development environment, offering comprehensive type definitions for all plugins. At their essence, each plugin operates as an interceptor, making them universally compatible with any Axios instance. This design choice guarantees a flexible and straightforward API, simplifying the integration process and elevating the overall user experience.
Discover the core functionalities that enhance the flexibility and power of our solution:
Elevate your application with our versatile set of built-in plugins, designed for comprehensive adaptability and robustness:
Project Dependencies
Please ensure you have the following dependencies installed in your project before proceeding:
Add to your project using NPM or Yarn:
NPM
npm install @axios-extensions/plugins-api
Yarn
yarn add @axios-extensions/plugins-api
Basic usage
api.ts file and import the plugins you want to use.// src/core/api.ts
// Import any plugin you want to use.
import {
HeaderRequestInterceptor,
JwtBearerTokenRequestInterceptor,
createApi,
} from "@axios-extensions/plugins-api";
// Create an instance of Axios with the plugins you want to use.
export const { api, installInterceptor } = createApi({
// Enable/disable the built-in error handler.
enableErrorHandler: true,
// Use undefined if you don't want to use a base URL.
// Uses the built-in base url plugin.
baseURL: () => "https://example.com/api",
interceptors: [
HeaderRequestInterceptor(() => ({ Accept: "application/ld+json" })), // Providing no method = any method.
HeaderRequestInterceptor(
() => ({ "Content-Type": "application/ld+json" }),
"post",
),
HeaderRequestInterceptor(
() => ({ "Content-Type": "application/ld+json" }),
"put",
),
HeaderRequestInterceptor(
() => ({ "Content-Type": "application/merge-patch+json" }),
"patch",
),
JwtBearerTokenRequestInterceptor(
() => "your-token",
["/api/login", "/api/refresh", "/api/excluded-route"],
),
],
});
export default api;
api instance in your application.// src/example.ts
import api from "./core/api";
// You can use axios as you normally would.
api.get("/images").then((r) => console.log(r.data));
// src/example.ts
import { HeaderRequestInterceptor } from "@axios-extensions/plugins-api";
import { api, installInterceptor } from "./core/api";
// No extra interceptor
api.get("/images").then((r) => console.log(r.data));
// Add an extra interceptor only for get calls
installInterceptor(
HeaderRequestInterceptor(() => ({ "X-Extra-Header": "extra" }), "get"),
);
api.get("/images").then((r) => console.log(r.data));
Note: By default Axios doesn't throw errors for status codes 4xx and 5xx. This plugin will so they can be handled correctly.
Enabling the error handler plugin will automatically return 3 error types:
ClientError (status code 4xx)ServerError (status code 5xx)NetworkError (no response)AxiosError (default AxiosError) (any other error not caught by the plugin)enableErrorHandler in your api.ts file.// src/core/api.ts
// ...
// Create an instance of Axios with the plugins you want to use.
export const { api, installInterceptor } = createApi({
// Toggle the built-in error handler.
enableErrorHandler: true,
//...
});
// ...
api instance in your application.// src/example.ts
import api from "./core/api";
// This will throw an ClientError
api
.get("https://httpstat.us/400")
.then((r) => console.log(r.data))
.catch((e) => {
if (e instanceof ClientError) {
console.log("Client error:", e);
} else if (e instanceof ServerError) {
console.log("Server error:", e);
} else if (e instanceof NetworkError) {
console.log("Network error:", e);
} else {
console.log("Another unknown error:", e);
}
});
The RefreshTokenPlugin is designed to automatically refresh your authentication token upon encountering a 401 status code. This plugin demands special handling and does not follow the standard installation procedure.
Once the token refresh operation concludes, it retries the original request, ensuring a uninterrupted continuation of your request.
// src/core/refreshToken.ts
import {
installInterceptor,
RefreshTokenResponseInterceptor,
api,
} from "./core/api";
const refreshTokenPlugin = RefreshTokenResponseInterceptor(
api, // Include the api instance, leveraging the automatic retry functionality.
() => api.post("/api/refresh", { refreshToken: "your-refresh" }),
["/api/login", "/api/refresh", "/api/excluded-route"],
);
installInterceptor(refreshTokenPlugin);
Note: Priority is used to determine the order in which the plugins are executed. The lower the number, the earlier the plugin is executed.
Example: A plugin with priority -100 will be executed before a plugin with priority 10.
// src/example-request-plugin.ts
import { installInterceptor } from "./core/api";
import type {
InternalAxiosRequestConfig,
AxiosError,
AxiosResponse,
} from "axios";
import { InterceptorType } from "@axios-extensions/plugins-api";
import type { InterceptorConfig } from "@axios-extensions/plugins-api";
export function MyCustomRequestPlugin(
baseUrlGetter: () => string,
): InterceptorConfig<InterceptorType.REQUEST> {
const myState = useSomeState();
async function resolved(
requestConfig: InternalAxiosRequestConfig,
): Promise<InternalAxiosRequestConfig> {
requestConfig.baseURL = myState.baseUrl.value;
return requestConfig;
}
return {
name: "MyCustomRequestPlugin",
type: InterceptorType.REQUEST,
priority: 1,
resolved,
};
}
Note: Priority is used to determine the order in which the plugins are executed. The lower the number, the earlier the plugin is executed.
Example: A plugin with priority -100 will be executed before a plugin with priority 10.
// src/example-response-plugin.ts
import { installInterceptor } from "./core/api";
import type { AxiosError, AxiosResponse } from "axios";
import { InterceptorType } from "@axios-extensions/plugins-api";
import type { InterceptorConfig } from "@axios-extensions/plugins-api";
export function MyCustomRequestPlugin(
baseUrlGetter: () => string,
): InterceptorConfig<InterceptorType.REQUEST> {
const myState = useSomeState();
async function resolved(
response: AxiosResponse,
): Promise<InternalAxiosRequestConfig> {
myState.error.value = "Success!";
return requestConfig;
}
async function rejected(
error: AxiosError,
): Promise<InternalAxiosRequestConfig> {
myState.error.value = error.message;
return requestConfig;
}
return {
name: "MyCustomResponsePlugin",
type: InterceptorType.RESPONSE,
priority: 1,
resolved,
rejected,
};
}
Contributions are welcome! Here are several ways you can contribute:
git clone <your-forked-repo-url>
git switch -b new-feature-x
git commit -am 'Implemented new feature x.'
git push origin new-feature-x
Once your PR is reviewed and approved, it will be merged into the main branch.
This project is protected under the MIT License. For more details, refer to the LICENSE file.
FAQs
Solves the missing priority / add / remove interceptors in Axios
We found that @axios-extensions/plugins-api demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Security News
Multiple high-impact npm maintainers confirm they have been targeted in the same social engineering campaign that compromised Axios.

Security News
Axios compromise traced to social engineering, showing how attacks on maintainers can bypass controls and expose the broader software supply chain.

Security News
Node.js has paused its bug bounty program after funding ended, removing payouts for vulnerability reports but keeping its security process unchanged.