
Company News
Socket Joins New OpenJS Program to Fund Node.js Security Work
Socket is joining the OpenJS Security Stewardship Program to fund Node.js vulnerability research, maintainer remediation, and security releases.
interceptor-builder
Advanced tools
A modern collection of reusable utility functions for JavaScript and TypeScript, designed to simplify everyday development tasks.
A clean and extendable interceptor builder for chaining and organizing multiple request/response interceptors.
npm install interceptor-builder
First, create an instance of your preferred HTTP client. In this example, we'll use Axios.
import axios from "axios";
const instance = axios.create({
baseURL: "http://localhost:5173/",
});
Next, create a custom interceptor by implementing the Interceptor interface.
import type { Interceptor, Req, Res, Instance } from "interceptor-builder";
export default class MyInterceptor implements Interceptor {
public instance: Instance;
constructor(instance: Instance) {
this.instance = instance;
}
intercept(req: Req, res: Res): Instance {
req.use(
(config) => {
console.log("Request interceptor");
return config;
},
(error) => Promise.reject(error)
);
res.use(
(response) => {
console.log("Response interceptor");
return response;
},
(error) => Promise.reject(error)
);
return this.instance;
}
}
Finally, use the InterceptorBuilder to chain your interceptors and build the final instance.
import InterceptorBuilder from "interceptor-builder";
import MyInterceptor from "./MyInterceptor";
import LoadingInterceptor from "./LoadingInterceptor";
import TokenInterceptor from "./TokenInterceptor";
const instance = axios.create({
baseURL: "http://localhost:5173/",
});
const enhancedInstance = new InterceptorBuilder(instance).use(MyInterceptor).use(LoadingInterceptor).use(TokenInterceptor).build();
export default enhancedInstance;
Here are some examples of custom interceptors you can create.
loading.interceptor.tsThis interceptor shows a loading indicator during a request.
import type { AxiosInstance } from "axios";
import type { Interceptor, Req, Res } from "interceptor-builder";
export default class LoadingInterceptor implements Interceptor {
public instance;
constructor(instance: AxiosInstance) {
this.instance = instance;
}
private setLoading(loading: boolean) {
const event = new CustomEvent("loading", { detail: loading });
window.dispatchEvent(event);
}
intercept(request: Req, response: Res) {
request.use(
(config) => {
this.setLoading(true);
return config;
},
(error) => {
this.setLoading(false);
return Promise.reject(error);
}
);
response.use(
(res) => {
this.setLoading(false);
return res;
},
(error) => {
this.setLoading(false);
return Promise.reject(error);
}
);
return this.instance;
}
}
token.interceptor.tsThis interceptor adds an authentication token to the request headers and handles token refreshing.
import type { AxiosError, AxiosInstance } from "axios";
import axios from "axios";
import type { Interceptor, Req, Res } from "interceptor-builder";
export default class TokenInterceptor implements Interceptor {
public instance;
constructor(instance: AxiosInstance) {
this.instance = instance;
}
protected clear = async () => {
localStorage.clear();
setTimeout(() => {
window.location.replace("/auth/login");
}, 50);
};
private refreshTokenApi = async () => {
try {
const { data } = await axios.get("https://dummyjson.com/auth/refresh");
localStorage.setItem("accessToken", data?.accessToken);
return data;
} catch (error) {
this.clear();
return error;
}
};
private getToken = async () => {
const token = {
accessToken: (localStorage.getItem("accessToken") as string) || "",
};
return token;
};
intercept(request: Req, response: Res) {
request.use(
async (config) => {
const token = await this.getToken();
if (token) config.headers.Authorization = `Bearer ${token.accessToken}`;
return config;
},
(error) => Promise.reject(error)
);
response.use(
(res) => res,
async (error: AxiosError) => {
try {
const status = error.response?.status;
const originalRequest = error.config as any;
if (status === 401 && !originalRequest?._retry) {
originalRequest._retry = true;
const token = await this.getToken();
if (!token.accessToken) return;
/*---refreshTokenApi---*/
const data = await this.refreshTokenApi();
if (data?.accessToken) {
originalRequest.headers["Authorization"] = `Bearer ${data?.accessToken}`;
return axios(originalRequest);
}
}
return Promise.reject(error);
} catch (error) {
return Promise.reject(error);
}
}
);
return this.instance;
}
}
InterceptorBuilderThe main class for building the interceptor chain.
| Method | Description |
|---|---|
use() | Adds an interceptor to the chain. |
build() | Builds the final instance with all the interceptors. |
InterceptorThe interface that all interceptors must implement.
| Property | Description |
|---|---|
instance | The HTTP client instance. |
intercept() | The method where you define your interceptor logic. |
The package also provides the following types:
Req: The request interceptor manager.Res: The response interceptor manager.Instance: The HTTP client instance.Contributions are welcome! Please feel free to submit a pull request or open an issue.
git checkout -b feature/your-feature).git commit -m 'Add some feature').git push origin feature/your-feature).This package is open-source and available under the ISC License.
FAQs
A modern collection of reusable utility functions for JavaScript and TypeScript, designed to simplify everyday development tasks.
The npm package interceptor-builder receives a total of 5 weekly downloads. As such, interceptor-builder popularity was classified as not popular.
We found that interceptor-builder demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.

Company News
Socket is joining the OpenJS Security Stewardship Program to fund Node.js vulnerability research, maintainer remediation, and security releases.

Security News
Two compromised GitHub Actions were re-enabled with malicious tags intact, exposing thousands of downstream repositories to Mini Shai-Hulud.

Research
/Security News
A malicious Firefox extension fetches its payload after installation to evade detection, steal Google session cookies, and automate account takeover.