Sub topic 3
Requests are immutable: using clone()
What this chapter assumes
You should be comfortable with TypeScript, Angular services and dependency injection, and basic HttpClient calls. You should also know what pipe, tap and catchError do in RxJS. This chapter covers one rule that every interceptor follows: an HttpRequest cannot be changed after it is created, so an interceptor builds a modified copy with clone().
Why requests are immutable
An interceptor receives an HttpRequest object and a next function. A natural first attempt is to change the request directly:
import { HttpInterceptorFn } from '@angular/common/http';
export const brokenInterceptor: HttpInterceptorFn = (req, next) => {
// Does not compile: 'headers' is a read-only property.
req.headers = req.headers.set('X-App', 'demo');
return next(req);
};TypeScript rejects this because the properties of HttpRequest are readonly. The restriction is deliberate, and it has three practical reasons.
- Retries stay predictable. A request can be sent more than once, for example when you retry after a failure. If one interceptor changed the original object, a second attempt would start from a modified request, and the changes could pile up.
- Interceptors cannot interfere with each other. Each interceptor sees the request that the previous one passed on. None of them can secretly change an object that another part of the code still holds.
- Callers keep what they built. The code that called
http.get(...)created a request description. Interceptors should not rewrite it behind the caller's back.
The same rule applies to HttpHeaders and HttpParams. Their methods such as set, append and delete do not change the object. They return a new one.
import { HttpHeaders } from '@angular/common/http';
const original = new HttpHeaders();
const changed = original.set('X-App', 'demo');
console.log(original.has('X-App')); // false
console.log(changed.has('X-App')); // trueA frequent bug is calling headers.set(...) and ignoring the return value. The call has no effect, and no error appears.
How clone() works
req.clone(update) returns a new HttpRequest. Every field you do not mention is copied from the original. Every field you do mention is replaced.
import { HttpInterceptorFn } from '@angular/common/http';
export const apiPrefixInterceptor: HttpInterceptorFn = (req, next) => {
const apiReq = req.clone({ url: `https://api.example.com${req.url}` });
return next(apiReq);
};The new request has the same method, body, headers, parameters and context as the original. Only the url is different. The interceptor passes apiReq to next. The original req is untouched.
The update object accepts these properties:
| Property | Effect |
|---|---|
| `url` | Replaces the request URL. |
| `method` | Replaces the HTTP method. |
| `body` | Replaces the body. Use `null` to remove it. |
| `headers` | Replaces the whole `HttpHeaders` object. |
| `params` | Replaces the whole `HttpParams` object. |
| `context` | Replaces the `HttpContext`. |
| `responseType` | Replaces the expected response type. |
| `reportProgress` | Turns progress events on or off. |
| `withCredentials` | Sets whether cookies are sent on cross-site requests. |
| `setHeaders` | Adds or overwrites individual headers, keeping the others. |
| `setParams` | Adds or overwrites individual query parameters, keeping the others. |
Replacing versus setting
The difference between headers and setHeaders causes real bugs, so it is worth stating clearly.
headersreplaces the entire header collection. Any header that was already on the request is gone unless you copy it.setHeaderstakes an object of names and values and merges it into the existing headers. A header with the same name is overwritten. All others stay.
The same distinction applies to params and setParams.
import { HttpHeaders, HttpInterceptorFn } from '@angular/common/http';
// Replaces: the request loses every header it had before.
export const replacingInterceptor: HttpInterceptorFn = (req, next) => {
return next(req.clone({ headers: new HttpHeaders({ 'X-App': 'demo' }) }));
};
// Merges: existing headers survive, X-App is added.
export const mergingInterceptor: HttpInterceptorFn = (req, next) => {
return next(req.clone({ setHeaders: { 'X-App': 'demo' } }));
};In most interceptors you want the merging form. Use headers only when you really mean to start from a blank set, or when you build the new HttpHeaders from req.headers yourself:
const headers = req.headers.set('X-App', 'demo').delete('X-Debug');
const cloned = req.clone({ headers });setHeaders can only add or overwrite. To remove a header, use the headers form with delete, as above.
Adding an Authorization header
The standard use of clone() is attaching a token. This version reads a token and clones only when there is one to attach.
import { HttpInterceptorFn } from '@angular/common/http';
import { inject } from '@angular/core';
import { AuthService } from './auth.service';
export const authInterceptor: HttpInterceptorFn = (req, next) => {
const token = inject(AuthService).getToken();
if (!token) {
return next(req);
}
const authReq = req.clone({
setHeaders: { Authorization: `Bearer ${token}` },
});
return next(authReq);
};Two details matter here.
- When there is no token, the interceptor passes the original
reqon. Cloning without a change is allowed but wasteful. - The interceptor passes
authReq, notreq, tonext. If you build the clone and then passreq, the header never leaves the browser. This is a common slip.
The chapter on inject() covers the inject(AuthService) call in detail. For now, treat it as a way to get a service inside the function.
The flow of a clone
The next diagram follows one request through an interceptor that clones it.
The caller still holds the original request. Nothing the interceptor did can be seen through that reference.
Cloning the body
The body is a special case. clone() copies the body by reference, so the new request points to the same object. It does not copy the contents. If an interceptor mutates the body object, the original request's body changes as well, which defeats the purpose of immutability.
To change the body safely, build a new object and pass it to clone():
import { HttpInterceptorFn } from '@angular/common/http';
export const stampInterceptor: HttpInterceptorFn = (req, next) => {
if (req.method !== 'POST' || typeof req.body !== 'object' || req.body === null) {
return next(req);
}
const stamped = { ...(req.body as Record<string, unknown>), sentAt: Date.now() };
return next(req.clone({ body: stamped }));
};The spread creates a new object, so the caller's body stays as it was. Note that a spread is a shallow copy. Nested objects are still shared, so do not edit them in place either. Also check the body type first. A FormData object or a Blob is not a plain object, and spreading it would give you the wrong result.
Edge cases
- Clone once, in the order you need. If several changes are needed, put them into one
clone()call. Callingclone()repeatedly works, but each call creates another object. - Passing an unchanged clone is harmless.
req.clone()with no argument produces an equal copy. It does nothing useful, though. - Do not store the request for later changes. If you keep a reference to
reqand expect it to reflect later changes, it will not. Eachclone()is a separate object. - Cloning does not resend the request. A request is only sent when something subscribes to the observable that
nextreturns. Cloning just builds the description. - Changing
methodis legal but rarely wise. Switching aGETto aPOSTin an interceptor will confuse the code that made the call. Prefer to handle that at the call site. - A URL change is not a redirect. The browser never sees the old URL. Other interceptors further down the chain see the new one.
Checking your work
You can confirm that the original request is unchanged by writing a small interceptor that compares the two objects:
import { HttpInterceptorFn } from '@angular/common/http';
export const proofInterceptor: HttpInterceptorFn = (req, next) => {
const cloned = req.clone({ setHeaders: { 'X-Proof': '1' } });
console.log(req === cloned); // false
console.log(req.headers.has('X-Proof')); // false
console.log(cloned.headers.has('X-Proof')); // true
return next(cloned);
};The three logged values show that the clone is a different object, that the original has no new header, and that the clone does.
Exercise
An interceptor contains const withHeader = req.clone({ setHeaders: { 'X-Trace': 'on' } }); return next(req);. The server never receives the X-Trace header. Why, and how do you fix it?
Show answer
The interceptor creates the clone but passes the original request to next, so the new header is never sent. Change the last line to return next(withHeader);.
Exercise
A request already has the headers Accept and X-Debug. One interceptor calls req.clone({ headers: new HttpHeaders({ 'X-App': 'demo' }) }), and another calls req.clone({ setHeaders: { 'X-App': 'demo' } }). Which headers does each resulting request carry?
Show answer
The first request carries only X-App, because headers replaces the whole collection. The second carries Accept, X-Debug and X-App, because setHeaders merges into the existing headers.
Exercise
Write an interceptor that adds the query parameter lang=en to every request without removing the parameters the caller set.
Show answer
export const langInterceptor: HttpInterceptorFn = (req, next) => next(req.clone({ setParams: { lang: 'en' } }));