Sub topic 9
Working with responses and events: logging and timing
This chapter assumes you can write a functional interceptor, register it with withInterceptors, and use pipe, tap, and map in RxJS. It covers what the observable returned by next emits and how to log, time, and transform responses.
What `next(req)` emits
Most people think of an HTTP call as one request and one response. The observable returned by next(req) is richer than that. It emits HttpEvent values, and a single request can emit several of them.
An HttpEvent is a union of these types. Each has a type field from the HttpEventType enum.
| Event type | Class | When it appears |
|---|---|---|
| `HttpEventType.Sent` | `{ type: 0 }` | The request has been sent. |
| `HttpEventType.UploadProgress` | `HttpProgressEvent` | Only with `reportProgress: true`, while a body uploads. |
| `HttpEventType.ResponseHeader` | `HttpHeaderResponse` | Only with `reportProgress: true`, when headers arrive. |
| `HttpEventType.DownloadProgress` | `HttpProgressEvent` | Only with `reportProgress: true`, while a body downloads. |
| `HttpEventType.Response` | `HttpResponse` | The full response has arrived. |
| `HttpEventType.User` | custom | Reserved for custom events. |
For an ordinary request with default options, the observable emits one HttpResponse and then completes. This is why interceptors check event.type. When a call uses reportProgress, the same interceptor sees several events, and code that assumes "the first emission is the response" will break.
The next diagram shows how events flow back through the chain.
Observing events with `tap`
The tap operator runs a side effect for each emission without changing it. That makes it the right tool for logging and timing, because the interceptor does not alter the response.
import { HttpEventType, HttpInterceptorFn } from '@angular/common/http';
import { tap } from 'rxjs';
export const loggingInterceptor: HttpInterceptorFn = (req, next) => {
const started = Date.now();
return next(req).pipe(
tap((event) => {
if (event.type === HttpEventType.Response) {
console.log(`${req.method} ${req.urlWithParams} -> ${event.status} in ${Date.now() - started}ms`);
}
}),
);
};Three details matter here.
startedis captured when the interceptor function runs, which is when the request enters this interceptor. The measured time therefore includes every interceptor after this one in the chain, plus the network round trip.- The check
event.type === HttpEventType.Responsenarrows the type. Inside theif, TypeScript knowseventis anHttpResponse, soevent.statuscompiles. Without the check,eventis the whole union andstatusis not available on every member. req.urlWithParamsincludes the query string.req.urldoes not. UseurlWithParamswhen logs need to distinguish/items?page=1from/items?page=2.
The interceptor returns the same observable shape it received. Callers of http.get(...) see no difference.
Where the timer starts matters
Because elapsed time covers everything downstream, the registration order changes what you measure. Suppose authInterceptor does slow asynchronous work before calling next, and the logger is registered first:
provideHttpClient(withInterceptors([loggingInterceptor, authInterceptor]));The logger's timer starts before the auth work, so the logged time includes it. If the logger is placed last, its timer starts after the auth work and measures closer to the network time alone. Neither is wrong, but you should decide which number you want and place the interceptor to match. Chapter 6 covers the ordering rules in full.
Timing observable lifetime, not only responses
The code above only logs when a response arrives. A request that fails never emits a Response event, so tap with a single callback logs nothing for failures. To log both outcomes, pass an observer object to tap:
import { HttpErrorResponse, HttpEventType, HttpInterceptorFn } from '@angular/common/http';
import { tap } from 'rxjs';
export const timingInterceptor: HttpInterceptorFn = (req, next) => {
const started = performance.now();
const elapsed = () => Math.round(performance.now() - started);
return next(req).pipe(
tap({
next: (event) => {
if (event.type === HttpEventType.Response) {
console.log(`${req.method} ${req.urlWithParams} ok ${event.status} (${elapsed()}ms)`);
}
},
error: (error: HttpErrorResponse) => {
console.warn(`${req.method} ${req.urlWithParams} failed ${error.status} (${elapsed()}ms)`);
},
}),
);
};performance.now() is a better timer than Date.now() for durations. It is monotonic, so it is not affected by the system clock being adjusted while a request is in flight.
The error callback of tap does not catch or handle the error. The error continues to propagate to the caller. That is the main difference between tap and catchError, which the next chapter uses to handle errors.
There is also a third case. If the caller unsubscribes before the response arrives, for example because a component was destroyed or switchMap cancelled the call, neither next nor error fires. To log cancellations, use finalize:
import { HttpInterceptorFn } from '@angular/common/http';
import { finalize } from 'rxjs';
export const lifetimeInterceptor: HttpInterceptorFn = (req, next) => {
const started = performance.now();
return next(req).pipe(
finalize(() => {
console.log(`${req.method} ${req.url} finished after ${Math.round(performance.now() - started)}ms`);
}),
);
};finalize runs on completion, error, and unsubscribe. It cannot tell you which of the three happened, so combine it with tap when you need the outcome.
Reading response details
Inside the Response branch you have the whole HttpResponse. These properties are the ones you will use most.
event.statusandevent.statusTextgive the HTTP status.event.headers.get('name')reads a response header. Header lookup is case-insensitive.event.bodyis the parsed body, typed asunknownin an interceptor because the interceptor does not know the endpoint's type.event.urlis the final URL, which can differ from the request URL after redirects.
A common use is reading a correlation or rate-limit header:
import { HttpEventType, HttpInterceptorFn } from '@angular/common/http';
import { tap } from 'rxjs';
export const rateLimitInterceptor: HttpInterceptorFn = (req, next) => {
return next(req).pipe(
tap((event) => {
if (event.type === HttpEventType.Response) {
const remaining = event.headers.get('X-RateLimit-Remaining');
if (remaining !== null && Number(remaining) < 10) {
console.warn(`Rate limit nearly reached: ${remaining} requests left`);
}
}
}),
);
};Cross-origin responses expose only a small set of headers to JavaScript. If the server does not list a header in Access-Control-Expose-Headers, headers.get returns null even though the header is visible in the browser's network tab.
Transforming responses with `map`
tap observes. map changes what flows to the caller. Because responses are immutable just as requests are, you replace an HttpResponse with a clone by using event.clone({ body: ... }).
import { HttpEventType, HttpInterceptorFn, HttpResponse } from '@angular/common/http';
import { map } from 'rxjs';
interface Envelope {
data: unknown;
}
export const unwrapInterceptor: HttpInterceptorFn = (req, next) => {
return next(req).pipe(
map((event) => {
if (event instanceof HttpResponse && isEnvelope(event.body)) {
return event.clone({ body: event.body.data });
}
return event;
}),
);
};
function isEnvelope(body: unknown): body is Envelope {
return typeof body === 'object' && body !== null && 'data' in body;
}This interceptor assumes the backend wraps every payload as { "data": ... } and unwraps it so services receive the inner value. Note the following.
- The
mapcallback must return anHttpEventon every path. Returningundefinedfor non-response events breaks the stream. Here the finalreturn eventpasses progress and sent events through untouched. - The check
event instanceof HttpResponseworks as an alternative toevent.type === HttpEventType.Response. Both narrow the type. Usinginstanceofcan fail if two copies of the library are loaded, so thetypecheck is the safer choice in most code. - Response transformation hides the real shape of the data from anyone reading the service code. Use it sparingly and document it. A mapping that applies only to some endpoints is a sign that the logic belongs in a service, not an interceptor.
Progress events
By default, HttpClient hides progress events. If a call sets reportProgress: true and observe: 'events', the interceptor sees them and so does the caller:
this.http.post('/api/upload', formData, {
reportProgress: true,
observe: 'events',
}).subscribe((event) => {
if (event.type === HttpEventType.UploadProgress && event.total) {
console.log(`${Math.round((100 * event.loaded) / event.total)}%`);
}
});An interceptor that wants to log only the final result already handles this correctly, because it checks for HttpEventType.Response and ignores the others. An interceptor that logs every event would print many lines for one upload. Decide deliberately which events you care about.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Logging without checking `event.type` | Output appears for every event, including progress events. | Branch on `HttpEventType.Response`. |
| Using only a `next` callback in `tap` | Failed requests are never logged. | Use `tap({ next, error })`. |
| Returning nothing from `map` for non-response events | The stream breaks or emits `undefined`. | Return `event` on every path. |
| Mutating `event.body` in place | The change may affect cached or shared objects. | Return `event.clone({ body })`. |
| Calling `console.log` with the whole response body | Sensitive data lands in logs. | Log status, method, and URL only. |
| Treating `Date.now()` differences as precise | The value can jump if the clock changes. | Use `performance.now()`. |
Exercise
A logging interceptor uses tap((event) => console.log(event.status)) and fails to compile. Why does it fail, and what is the fix? Also, what happens if you fix it but the server returns a 500 status?
Show answer
next(req) emits the HttpEvent union, and only HttpResponse and HttpHeaderResponse have a status property, so TypeScript rejects the access. Fix it by narrowing with if (event.type === HttpEventType.Response) before reading event.status. With a 500, HttpClient does not emit a Response event. It errors the observable with an HttpErrorResponse, so a tap that only has a next callback logs nothing. To log failures, use tap({ next: ..., error: (e: HttpErrorResponse) => ... }).
Exercise
You register [loggingInterceptor, authInterceptor], and authInterceptor waits 200 ms for a token before it calls next. The logging interceptor starts its timer when it runs. Does the logged duration include the 200 ms? What would you change to exclude it?
Show answer
Yes. loggingInterceptor runs first, so its timer starts before authInterceptor waits, and the elapsed time includes the 200 ms. To exclude it, register the logger after the auth interceptor: withInterceptors([authInterceptor, loggingInterceptor]).