Axios interceptors for auth headers
cross-cutting request handling.
interceptors are hooks that run before requests or after responses, centralizing concerns like auth, logging, and token refresh.
attaching the token manually in every call site.
WHAT THIS TESTS Whether you understand interceptors as middleware for HTTP, letting you handle concerns once rather than at every call site, and whether you can write one correctly.
A GOOD ANSWER COVERS Axios interceptors are functions registered on an instance that run automatically. A request interceptor receives the outgoing config, mutates or augments it, and returns it before the request is sent. A response interceptor receives the response or error and can transform data, log, or react, for example catching a 401 and refreshing the token before retrying the original request. The canonical use is injecting an Authorization header so no call site repeats it. You typically register interceptors on a dedicated axios instance so they apply consistently and remain testable, and you read the token from secure storage rather than memory.
COMMON WRONG ANSWERS Forgetting to return config from a request interceptor, which sends an undefined config; setting the token synchronously when it lives in async secure storage; or not guarding against infinite retry loops when the refresh itself fails. Adding the header in every component is the anti-pattern interceptors exist to remove.
LIKELY FOLLOW-UPS How do you handle async token retrieval inside an interceptor? How do you prevent multiple parallel 401s from triggering many refreshes? How do you eject an interceptor in tests?
ONE CONCRETE EXAMPLE const api = axios.create({ baseURL }); api.interceptors.request.use(async config => { const token = await getToken(); if (token) config.headers.Authorization = 'Bearer ' + token; return config; }); Now every request through api carries the bearer token automatically. A paired response interceptor can detect a 401, call refresh once, update storage, and replay the failed request, keeping all auth logic in one place.
Read the original → axios.rest
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.