What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
A single HTTP interceptor can both attach a bearer token to outgoing API calls and record what each request did. That combination is useful, but it also puts two risks in one place. The logger can copy credentials into files that outlive the token, and the injector can send a valid token to a destination it was never meant for. The safe pattern is to log outcomes rather than credentials, and to attach a token only to requests bound for the API that issued it.
What interceptors do
An interceptor is a middleware-style hook that sees every request before it is sent and every response before the caller receives it. Teams use this layer for cross-cutting work that should behave the same way everywhere: logging, adding or changing headers, and modifying responses. In Axios, interceptors are registered on an instance with instance.interceptors.request.use() and instance.interceptors.response.use(). They can also be removed with eject() or cleared, which matters when an application needs to change its chain during its lifecycle.
As an Amazon Associate I earn from qualifying purchases.
Attach the current bearer token on every request
Read the token inside a request interceptor rather than once when the instance is created. A token captured at construction time goes stale as soon as it is refreshed, and the instance keeps sending the old value. Read it per request instead, and set the header with the Bearer scheme.
Do not confuse this with Axios’s auth option. That option configures HTTP Basic authentication and does not produce a bearer header. Use the interceptor for bearer tokens.
#1 Best Overall
api.interceptors.request.use((config) => {
const token = getCurrentAccessToken();
if (token && isTrustedApiTarget(config.url)) {
config.headers.set('Authorization', `Bearer ${token}`);
}
return config;
});
The isTrustedApiTarget check is implementation guidance, not something Axios prescribes. It is the line that keeps “automatic” from meaning “sent everywhere.” Token retrieval and storage are your application’s decisions. Browser storage is not safe by default for every token, so choose a storage location deliberately and keep token lifetimes short rather than using a long-lived token as the example in production code.
Why the injector should check its destination
A bearer token works for whoever holds it. Nothing in the header proves that the request was meant for the server that issued the token. If the interceptor attaches the token to every URL the client touches, a redirect, a misconfigured base URL, or a third-party call made through the same instance will carry the credential along. Keep one client instance scoped to one API where you can, and compare the target against an explicit list before adding the header.
Order and asynchronous behavior
Request and response interceptors run in opposite orders, and that changes what each hook sees.
Free tools Windows power users keep installed
One-click scans. No signup required.
Rank #2
| Interceptor type | Execution order in Axios | Practical effect |
|---|---|---|
| Request | Last registered runs first (reverse registration order) | A logger registered after the token injector runs before the header is set |
| Response | First registered runs first (registration order) | A response handler registered first sees the response first |
Request interceptors are asynchronous by default. Axios accepts a synchronous flag in the options argument of use() for handlers that do no asynchronous work. An async token lookup needs the default asynchronous mode, and the request waits for it. Confirm both the order and the timing in the Axios version you ship, because the documented behavior is tied to the v1.x line.
Troubleshooting a hook that runs in the wrong order
- List the request interceptors in the order they are registered. Remember that the last one added runs first.
- Find the hook that reads or logs the request. If it runs before the token injector, the request it sees has no
Authorizationheader. That is correct for a logger that should never record the token, but wrong for a check that expects an authenticated request. - If the order is right and the header is still missing, check whether your token function is async and whether a previous hook threw or returned a value you did not expect.
- Reproduce with a request to a local test server that echoes headers, so you can see what actually left the client without writing the token to a shared log.
Header values and control characters
Axios’s AxiosHeaders strips CR, LF, and other C0 control bytes when a header is set, which helps block header injection. Treat this as a library safeguard only. Validate untrusted header values in your own code, and do not rely on the library to make a token safe.
What to log, and what never to log
Logging should answer “what happened to this request?” The OkHttp logging interceptor’s documentation warns that its detailed HEADERS and BODY levels can expose Authorization and Cookie headers as well as request and response bodies, and it recommends using those levels only in a controlled way or in a non-production environment. That README comes from an Android source mirror and may describe an older release, so check the level behavior against the version in your dependency file before relying on it.
Rank #3
OWASP’s Logging Cheat Sheet makes the same point from the security side. Values such as access tokens and session identifiers should generally be removed, masked, sanitized, hashed, or encrypted rather than written as-is. Log data itself also needs protection against unauthorized access, modification, and deletion.
Recommended Free Tools
The following allow-list is an editorial recommendation derived from that guidance. Neither library requires this exact schema.
| Field | Log by default? | Reason |
|---|---|---|
| HTTP method | Yes | Needed to group requests and spot unexpected verbs |
Route template (for example /orders/:id) |
Yes | Shows the endpoint without the identifiers and query values inside a full URL |
| Full URL with query string | No | Query parameters can carry tokens or personal data |
| Status code and duration | Yes | Shows outcome and latency |
| Correlation ID | Yes | Links client and server records for one request |
Authorization header |
No | Contains the bearer credential |
Cookie header |
No | Can carry session identifiers |
| Request and response bodies | No | Often contain personal or sensitive content |
When you need deeper logging
Sometimes a support investigation requires more than the allow-list. If you turn on detailed logging temporarily, restrict it to a non-production environment or a tightly controlled window, limit who can read the output, and set a short retention period. Redaction must happen before the log sink receives the data. Scrubbing a file after it has been written leaves copies in shipping pipelines, backups, and dashboards.
Rank #4
- API Security in Action
- Manning Publications
- ABIS BOOK
Events that help investigations
OWASP identifies several security and operational events that are useful to record: authentication successes and failures, authorization failures, access to sensitive data, and network failures. These events are more useful for diagnosis than a copy of every header. Choose fields and collection practices that are lawful and proportionate to what your system does.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Token scope: where automatic injection goes wrong
OWASP’s OAuth2 Cheat Sheet describes bearer tokens as credentials that grant access to whoever possesses them. It recommends audience restriction, preferably to a single resource server, so that a leaked token is useless elsewhere. For use cases that warrant extra protection against replay, it describes sender-constrained tokens, such as mTLS-bound or DPoP-bound access tokens, which are bound to a key the client holds.
In practice, “automatic” should mean consistently attached to the requests an API was built to receive. It should not mean attached to every outbound call. A token issued for one resource server should not travel to an analytics endpoint, a CDN, or a partner host that happens to share the client instance.
Best Value
Trade-offs to decide explicitly
- Diagnostic detail versus secret exposure. Method, route, status, and timing give less detail but carry little risk. Full headers and bodies help troubleshooting while creating token, cookie, and personal-data exposure.
- Convenience versus credential scope. Attaching the token in one interceptor removes repeated setup from every call. The same convenience sends a usable credential wherever the interceptor runs unless you add a destination check.
- Synchronous hooks versus asynchronous preparation. A synchronous handler avoids Promise scheduling. Token acquisition that needs I/O requires an asynchronous hook, which the request waits on.
Common questions this setup answers
If you are asking how to add a bearer token to every Axios request, the answer is a request interceptor with a destination check, not a header on the instance. If you are asking how to log HTTP requests without leaking tokens, log the allow-list above and redact before the sink. If your request interceptor runs in the wrong order, check the reverse registration rule first.
The Bottom Line
Use one interceptor for both jobs only if you can answer three questions in code: which destinations receive the token, which fields the logger is allowed to record, and where redaction happens. If any of those answers depends on luck or on the default configuration, fix it before the code ships.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.




