Interceptors help add authentication tokens to your app's requests automatically. This keeps your app secure without repeating code.
Interceptors for authentication tokens in Angular
import { Injectable } from '@angular/core'; import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable() export class AuthInterceptor implements HttpInterceptor { intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { const token = 'your-auth-token'; const clonedReq = req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }); return next.handle(clonedReq); } }
The intercept method runs on every HTTP request.
Use req.clone() to avoid changing the original request.
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const token = localStorage.getItem('authToken');
if (token) {
const clonedReq = req.clone({
setHeaders: { Authorization: `Bearer ${token}` }
});
return next.handle(clonedReq);
}
return next.handle(req);
}intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const clonedReq = req.clone({
setHeaders: { 'Custom-Header': 'MyValue' }
});
return next.handle(clonedReq);
}This interceptor checks if a token exists in local storage. If yes, it adds it as a Bearer token in the Authorization header for every HTTP request. This way, your app sends the token automatically without extra code in components.
import { Injectable } from '@angular/core'; import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HTTP_INTERCEPTORS } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable() export class AuthInterceptor implements HttpInterceptor { intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { const token = localStorage.getItem('authToken'); if (token) { const clonedReq = req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }); return next.handle(clonedReq); } return next.handle(req); } } // Usage in app.module.ts providers array: // { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }
Remember to register your interceptor in the app module providers.
Interceptors run in the order they are provided.
Do not modify the original request directly; always clone it.
Interceptors add tokens to HTTP requests automatically.
They keep your app secure and code clean.
Always clone requests before modifying headers.
Practice
Solution
Step 1: Understand the role of interceptors
Interceptors are used to modify HTTP requests or responses globally in Angular.Step 2: Identify the use of tokens in interceptors
They commonly add authentication tokens to requests to keep the app secure without repeating code.Final Answer:
To automatically add authentication tokens to outgoing HTTP requests -> Option BQuick Check:
Interceptors add tokens = B [OK]
- Thinking interceptors create requests
- Believing interceptors block requests
- Assuming interceptors change URLs
Solution
Step 1: Recall Angular HttpRequest immutability
HttpRequest objects are immutable, so you must clone them to modify headers.Step 2: Use the clone method with headers.set()
The correct syntax is to call clone() and set the new header inside it.Final Answer:
request.clone({ headers: request.headers.set('Authorization', 'Bearer ' + token) }) -> Option DQuick Check:
Clone request with headers.set() = A [OK]
- Trying to modify headers directly without cloning
- Using non-existent methods like modifyHeaders or updateHeaders
- Not using the clone method
intercept(request: HttpRequest<any>, next: HttpHandler) {
const token = 'abc123';
const cloned = request.clone({
headers: request.headers.set('Authorization', `Bearer ${token}`)
});
return next.handle(cloned);
}Solution
Step 1: Check how the token is added
The code sets the Authorization header to 'Bearer ' plus the token string 'abc123'.Step 2: Understand string interpolation
The template string `Bearer ${token}` becomes 'Bearer abc123'.Final Answer:
Authorization: Bearer abc123 -> Option AQuick Check:
Header value = 'Bearer abc123' [OK]
- Forgetting 'Bearer ' prefix
- Using the literal word 'token' instead of variable
- Assuming header is not added
intercept(req: HttpRequest<any>, next: HttpHandler) {
const token = 'xyz';
req.headers.set('Authorization', 'Bearer ' + token);
return next.handle(req);
}Solution
Step 1: Understand HttpRequest immutability
HttpRequest headers cannot be changed directly; they are immutable.Step 2: Correct way is to clone the request with new headers
You must clone the request and set headers on the clone before passing it on.Final Answer:
Headers are immutable; must clone request before setting headers -> Option AQuick Check:
Immutable headers require cloning = A [OK]
- Trying to set headers directly on request
- Ignoring immutability of HttpRequest
- Not returning next.handle()
Solution
Step 1: Identify the need for conditional token addition
Only requests to 'api.example.com' should have the token added to avoid leaking tokens to other domains.Step 2: Use URL check before cloning and modifying request
Check request.url.includes('api.example.com') and then clone the request with the token header.Step 3: Avoid modifying requests without cloning or adding tokens globally
Modifying without cloning or adding tokens to all requests is insecure or incorrect.Final Answer:
Check if request.url.includes('api.example.com') before cloning and adding the token -> Option CQuick Check:
Conditional token addition by URL check = C [OK]
- Adding tokens to all requests blindly
- Modifying requests without cloning
- Trying to add tokens after request completes
Ready to prove it?
Pass the test and this pattern moves unknown
