How to backup and restore Axios instance configuration including interceptors and defaults?
0 reputation · 16 Feb 2022, 04:48 UTC
0 reputation · 16 Feb 2022, 04:48 UTC
When working with Axios in a long‑running application, you may need to persist the current state of an Axios instance—such as its base URL, default headers, timeout value, and any attached request/response interceptors—so that after a restart or reload the instance behaves exactly as before. What are the recommended approaches to serialize this configuration (including interceptors) and later restore it to a newly created Axios instance while preserving validation guarantees?
Consider scenarios where you want to backup the instance before performing a batch of requests and restore it afterward, or where you need to share a pre‑configured Axios setup across multiple modules or workers. Which Axios properties are serializable, which require manual handling (e.g., interceptor functions), and how can you verify that the restored instance produces identical request outcomes?
35275 reputation · 16 Feb 2022, 16:25 UTC
const defaultsBackup = JSON.parse(JSON.stringify(axiosInstance.defaults));// NOTE: This assumes the InterceptorManager exposes a handlers array; if not, you must re‑add the interceptors manually after restore.
const requestHandlers = axiosInstance.interceptors.request.handlers.map(h => ({ fulfilled: h.fulfilled, rejected: h.rejected }));
const responseHandlers = axiosInstance.interceptors.response.handlers.map(h => ({ fulfilled: h.fulfilled, rejected: h.rejected }));
const axiosBackup = { defaults: defaultsBackup, requestHandlers, responseHandlers };const restored = axios.create(axiosBackup.defaults);
axiosBackup.requestHandlers.forEach(h => restored.interceptors.request.use(h.fulfilled, h.rejected));
axiosBackup.responseHandlers.forEach(h => restored.interceptors.response.use(h.fulfilled, h.rejected));
axiosInstance (or recreate it from the original backup).Use comments to ask for clarification. Post a solution as an answer.
6,550 reputation · 16 Feb 2022, 13:34 UTC
From Axios 0.27 onward, instance.defaults.headers is an AxiosHeaders instance, not a plain object. A shallow spread will share mutable references, so a deep clone (e.g., structuredClone or a custom cloneHeaders helper) is required before snapshotting and later reassignment.
Request interceptors run in *reverse* registration order, while response interceptors run in registration order. When restoring, re‑register the handlers in the same sequence they were originally added to preserve the exact call chain.
Functions such as transformRequest, transformResponse, paramsSerializer, and validateStatus are closures and cannot be stringified. The safest approach is to keep references to the original functions and re‑attach them during restore.