Sub topic 3
Requests are immutable: using clone()
This chapter assumes you know TypeScript, can write a basic functional interceptor that takes req and next, and are comfortable with HttpClient and RxJS. It covers how to change a request inside an interceptor.
Why a request cannot be changed
Every property of an HttpRequest is readonly. You cannot write req.url = '...' or req.body = {...}, because TypeScript rejects it. Angular made requests immutable for three reasons:
- A request can be sent more than once, for example by a
retryoperator. A mutated request would carry earlier changes into the next attempt. - Several interceptors handle the same request in turn. If one of them mutated it, the others would see changes they did not expect.
- The code that created the request still holds a reference to it. Mutation would change an object the caller thinks is fixed.
The way to change a request is to make a modified copy and pass that copy to next.
Creating a copy with clone()
req.clone() returns a new HttpRequest. You pass an object that lists only the fields you want to change. Every other field is copied from the original.
import { HttpInterceptorFn } from '@angular/common/http';
export const apiUrlInterceptor: HttpInterceptorFn = (req, next) => {
if (!req.url.startsWith('/api')) {
return next(req);
}
const apiReq = req.clone({
url: `https://example.com${req.url}`,
setHeaders: { 'X-Client': 'web' },
});
return next(apiReq);
};This interceptor leaves requests that do not start with /api alone. For the others, it builds a copy with a full URL and an extra header, then forwards the copy. The original req is never modified.
Fields you can change
| Field in clone() | Effect |
|---|---|
| `url` | Replaces the URL |
| `body` | Replaces the body. `null` removes it |
| `headers` | Replaces the whole `HttpHeaders` object |
| `setHeaders` | Sets the listed headers. A header with the same name is overwritten |
| `params` | Replaces the whole `HttpParams` object |
| `setParams` | Sets the listed query parameters |
| `withCredentials` | Turns cookies and credentials on or off for cross-site requests |
| `responseType` | Changes how the response body is parsed |
| `context` | Replaces the `HttpContext` |
Use setHeaders and setParams when you want to add to what is already there. Use headers and params only when you want to replace everything.
Common mistakes
Headers and params are immutable too. Their set, append and delete methods return a new object and leave the original unchanged. This code looks right but does nothing:
import { HttpInterceptorFn } from '@angular/common/http';
export const brokenInterceptor: HttpInterceptorFn = (req, next) => {
req.headers.set('X-Client', 'web'); // the returned HttpHeaders is thrown away
return next(req);
};TypeScript does not warn about this, because the call is valid. The header is never sent. Prefer setHeaders in clone(), or assign the result of set to a variable and pass it as headers.
Two more points to remember:
- Clone is shallow. If the body is an object, the clone points to the same object. Do not mutate the body in place. Build a new object, for example
{ ...req.body, extra: 1 }, and pass it asbody. - Forward the clone, not the original. After you create
authReq, passauthReqtonext. Passingreqsilently drops your changes.
Exercise
An interceptor contains const copy = req.clone({ setHeaders: { 'X-Trace': '1' } }); return next(req);. Is the X-Trace header sent? Why or why not?
Show answer
No. clone() returns a new request and leaves req unchanged. The interceptor then forwards req, the original, so the copy with the header is never used. The fix is to return next(copy).