Using Axios Interceptors for Custom Retry Request Handling in TypeScript

How to use Axios interceptors for custom request handling in TypeScript.

Axios requests by Midjourney

Axios is a popular JavaScript library for making HTTP requests, and when combined with TypeScript, it allows for a more robust and maintainable codebase. In this blog post, we will explore how to use Axios interceptors for custom request handling in TypeScript.

An interceptor is a middleware function that can be inserted between the client and the server to modify the request or response. In Axios, you can add interceptors to the axios instance or to individual requests.

Here’s an example of adding a request interceptor to log all requests:

axios.interceptors.request.use((config: AxiosRequestConfig) => {
console.log(config);
return config;
});

In this example, the interceptor logs the config of the request before it is sent and returns the config unmodified. By using the AxiosRequestConfig type, TypeScript will ensure that the variable passed is of the correct type, which can prevent bugs and make development faster.

Another example of how to use interceptors is retrying failed requests, here’s an example of how to retry a failed request up to 3 times using TypeScript:

Step 1: Define Axios interceptor

import axios, { AxiosInstance, AxiosRequestConfig } from "axios";

const customAxiosApi: AxiosInstance = axios.create({
baseURL: "http://localhost:3000",
headers: {
"Content-Type": "application/json",
},
});


interface RetryConfig extends AxiosRequestConfig {
retry: number;
retryDelay: number;
}

const globalConfig: RetryConfig = {
retry: 3,
retryDelay: 1000,
};

customAxiosApi.interceptors.response.use(
(response) => response,
(error) => {
const { config } = err;

if (!config || !config.retry) {
return Promise.reject(err);
}
config.retry -= 1
const delayRetryRequest = new Promise<void>((resolve) => {
setTimeout(() => {
console.log("retry the request", config.url);
resolve();
}, config.retryDelay || 1000)
})
return delayRetryRequest.then(() => customAxiosApi(config));
}
);
export {customAxiosApi,globalConfig}

In this example, we defined an interface RetryConfig that extends the default AxiosRequestConfig and adds a new property retry. The interceptor checks if the request has a retries property, if not it rejects the error, otherwise it decrements the retries count and retries the request with the same config. By using TypeScript’s interfaces, we are able to define a custom type that extends the default `AxiosRequestConfig` , which allows us to be sure of the type of object we are handling and make development faster.

Then it defines a globalConfig object that sets retry to 3 and retryDelay to 1000. This globalConfig will be used as default when making a request with this Axios instance.

You can also use interceptors to add headers or authentication tokens to every request or to handle errors in a more elegant way.

Step 2: Usage of retry config

You can use the `globalConfig` to have retry ability on your requests.

axios.get("/", globalConfig).then((response) => {
return response.data;
});

axios.post("/", {}, globalConfig).then((response) => {
return response.data;
});

axios.patch("/", {}, globalConfig).then((response) => {
return response.data;
});

axios.delete("/", globalConfig).then((response) => {
return response.data;
});

In conclusion, Axios interceptors allow you to add custom Behavior to your requests and responses, such as logging requests, retrying failed requests, or adding headers. When used with TypeScript, it provides a more robust and maintainable codebase. It’s worth noting that interceptors are a powerful feature, so be careful when using them, and make sure to handle errors properly in a production environment.

You can also use this package to handle retry requests but it’s better not to add new packages to provide this ability when you know how to handle it.

https://www.npmjs.com/package/axios-retry

Let’s Connect

Thanks for reading my article. If you like my content, please consider buying me a coffee ☕.

Build apps with reusable components, just like Lego

Bit’s open-source tool help 250,000+ devs to build apps with components.

Turn any UI, feature, or page into a reusable component — and share it across your applications. It’s easier to collaborate and build faster.

Learn more

Split apps into components to make app development easier, and enjoy the best experience for the workflows you want:

Micro-Frontends

Design System

Code-Sharing and reuse

Monorepo

Learn more:


Using Axios Interceptors for Custom Retry Request Handling in TypeScript was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Bits and Pieces - Medium and was authored by Farnam Homayounfard

How to use Axios interceptors for custom request handling in TypeScript.

Axios requests by Midjourney

Axios is a popular JavaScript library for making HTTP requests, and when combined with TypeScript, it allows for a more robust and maintainable codebase. In this blog post, we will explore how to use Axios interceptors for custom request handling in TypeScript.

An interceptor is a middleware function that can be inserted between the client and the server to modify the request or response. In Axios, you can add interceptors to the axios instance or to individual requests.

Here’s an example of adding a request interceptor to log all requests:

axios.interceptors.request.use((config: AxiosRequestConfig) => {
console.log(config);
return config;
});

In this example, the interceptor logs the config of the request before it is sent and returns the config unmodified. By using the AxiosRequestConfig type, TypeScript will ensure that the variable passed is of the correct type, which can prevent bugs and make development faster.

Another example of how to use interceptors is retrying failed requests, here’s an example of how to retry a failed request up to 3 times using TypeScript:

Step 1: Define Axios interceptor

import axios, { AxiosInstance, AxiosRequestConfig } from "axios";

const customAxiosApi: AxiosInstance = axios.create({
baseURL: "http://localhost:3000",
headers: {
"Content-Type": "application/json",
},
});


interface RetryConfig extends AxiosRequestConfig {
retry: number;
retryDelay: number;
}

const globalConfig: RetryConfig = {
retry: 3,
retryDelay: 1000,
};

customAxiosApi.interceptors.response.use(
(response) => response,
(error) => {
const { config } = err;

if (!config || !config.retry) {
return Promise.reject(err);
}
config.retry -= 1
const delayRetryRequest = new Promise<void>((resolve) => {
setTimeout(() => {
console.log("retry the request", config.url);
resolve();
}, config.retryDelay || 1000)
})
return delayRetryRequest.then(() => customAxiosApi(config));
}
);
export {customAxiosApi,globalConfig}

In this example, we defined an interface RetryConfig that extends the default AxiosRequestConfig and adds a new property retry. The interceptor checks if the request has a retries property, if not it rejects the error, otherwise it decrements the retries count and retries the request with the same config. By using TypeScript's interfaces, we are able to define a custom type that extends the default `AxiosRequestConfig` , which allows us to be sure of the type of object we are handling and make development faster.

Then it defines a globalConfig object that sets retry to 3 and retryDelay to 1000. This globalConfig will be used as default when making a request with this Axios instance.

You can also use interceptors to add headers or authentication tokens to every request or to handle errors in a more elegant way.

Step 2: Usage of retry config

You can use the `globalConfig` to have retry ability on your requests.

axios.get("/", globalConfig).then((response) => {
return response.data;
});

axios.post("/", {}, globalConfig).then((response) => {
return response.data;
});

axios.patch("/", {}, globalConfig).then((response) => {
return response.data;
});

axios.delete("/", globalConfig).then((response) => {
return response.data;
});

In conclusion, Axios interceptors allow you to add custom Behavior to your requests and responses, such as logging requests, retrying failed requests, or adding headers. When used with TypeScript, it provides a more robust and maintainable codebase. It’s worth noting that interceptors are a powerful feature, so be careful when using them, and make sure to handle errors properly in a production environment.

You can also use this package to handle retry requests but it’s better not to add new packages to provide this ability when you know how to handle it.

https://www.npmjs.com/package/axios-retry

Let’s Connect

Thanks for reading my article. If you like my content, please consider buying me a coffee ☕.

Build apps with reusable components, just like Lego

Bit’s open-source tool help 250,000+ devs to build apps with components.

Turn any UI, feature, or page into a reusable component — and share it across your applications. It’s easier to collaborate and build faster.

Learn more

Split apps into components to make app development easier, and enjoy the best experience for the workflows you want:

Micro-Frontends

Design System

Code-Sharing and reuse

Monorepo

Learn more:


Using Axios Interceptors for Custom Retry Request Handling in TypeScript was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Bits and Pieces - Medium and was authored by Farnam Homayounfard


Print Share Comment Cite Upload Translate Updates
APA

Farnam Homayounfard | Sciencx (2023-02-17T17:05:37+00:00) Using Axios Interceptors for Custom Retry Request Handling in TypeScript. Retrieved from https://www.scien.cx/2023/02/17/using-axios-interceptors-for-custom-retry-request-handling-in-typescript/

MLA
" » Using Axios Interceptors for Custom Retry Request Handling in TypeScript." Farnam Homayounfard | Sciencx - Friday February 17, 2023, https://www.scien.cx/2023/02/17/using-axios-interceptors-for-custom-retry-request-handling-in-typescript/
HARVARD
Farnam Homayounfard | Sciencx Friday February 17, 2023 » Using Axios Interceptors for Custom Retry Request Handling in TypeScript., viewed ,<https://www.scien.cx/2023/02/17/using-axios-interceptors-for-custom-retry-request-handling-in-typescript/>
VANCOUVER
Farnam Homayounfard | Sciencx - » Using Axios Interceptors for Custom Retry Request Handling in TypeScript. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2023/02/17/using-axios-interceptors-for-custom-retry-request-handling-in-typescript/
CHICAGO
" » Using Axios Interceptors for Custom Retry Request Handling in TypeScript." Farnam Homayounfard | Sciencx - Accessed . https://www.scien.cx/2023/02/17/using-axios-interceptors-for-custom-retry-request-handling-in-typescript/
IEEE
" » Using Axios Interceptors for Custom Retry Request Handling in TypeScript." Farnam Homayounfard | Sciencx [Online]. Available: https://www.scien.cx/2023/02/17/using-axios-interceptors-for-custom-retry-request-handling-in-typescript/. [Accessed: ]
rf:citation
» Using Axios Interceptors for Custom Retry Request Handling in TypeScript | Farnam Homayounfard | Sciencx | https://www.scien.cx/2023/02/17/using-axios-interceptors-for-custom-retry-request-handling-in-typescript/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.