跪拜 Guibai
← All articles
Frontend · Backend

Axios Interceptors End the Tedium of Attaching JWTs to Every Request

By 东风破_ ·
Read original on juejin.cn ↗ Google Translate ↗ Alt translation

Scattering authentication logic across every API call creates a maintenance nightmare as projects grow. Centralizing token attachment in an interceptor keeps business code focused on data fetching and makes the entire request pipeline auditable in one place.

Summary

Manually adding an Authorization header to every Axios call is brittle and repetitive. A request interceptor on a shared Axios instance inspects each outgoing request, pulls the stored JWT from localStorage, and injects the Bearer token into the headers before the request leaves the browser. The result is that individual API modules like user.js or repo.js contain zero token logic — they simply declare which endpoint to hit. The interceptor also becomes the natural home for other cross-cutting concerns: unified headers, request logging, parameter transformation, loading indicators, and error handling. The chain completes when the server extracts the token from the Authorization header, strips the Bearer prefix, and verifies the JWT.

Takeaways
An Axios request interceptor runs before every request made with a given instance, allowing token injection without touching individual API calls.
Tokens are read from localStorage inside the interceptor, not from component state, so the logic stays decoupled from React’s render cycle.
The Bearer prefix must include a trailing space — omitting it produces an invalid header that fails server-side prefix checks.
API modules that import the configured Axios instance contain no Authorization code, achieving a clean separation of concerns.
Interceptors can also handle logging, loading states, parameter normalization, and error responses uniformly across all endpoints.
The server extracts the token by slicing off the 'Bearer ' prefix and then passes the raw token to jwt.verify.
Conclusions

Many frontend authentication tutorials skip the interceptor step, leaving beginners to copy-paste headers into every call — a habit that scales poorly past three endpoints.

The Bearer-prefix formatting detail is a small but common source of silent auth failures that are hard to debug without inspecting raw request headers.

Using localStorage as the token source inside an interceptor assumes a single-tab, single-user model; multi-tab or multi-account scenarios would need a different synchronization strategy.

Concepts & terms
Axios request interceptor
A middleware function registered on an Axios instance that transforms or augments the request config before every HTTP call is dispatched.
Bearer Token
An authentication token sent in the Authorization header with the format 'Bearer <token>', where the space after Bearer is required by the HTTP authentication scheme.
Source: juejin.cn ↗ Google Translate ↗ Backup ↗