Sub topic 9
Working with responses and events: logging and timing
This chapter assumes you can write a functional interceptor and register it with withInterceptors. It also assumes you know the RxJS operators pipe and tap. Earlier chapters changed the outgoing request. Here you work on the other half of the chain, the response coming back.
What next returns
next(req) returns an Observable<HttpEvent<unknown>>. It does not return a single response. The observable can emit several events over one request's lifetime.
| Event type | When it is emitted |
|---|---|
| `HttpEventType.Sent` | The request has been dispatched |
| `HttpEventType.UploadProgress` / `DownloadProgress` | Only if the request sets `reportProgress: true` |
| `HttpEventType.ResponseHeader` | Headers have arrived |
| `HttpEventType.Response` | The full response has arrived |
Interceptors see every event. A caller that uses the default observe: 'body' sees only the body. Because of this difference, an interceptor must check the event type before it reads status or body.
Logging status and elapsed time
Record the start time before you call next. Then use tap to observe the events without changing them.
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`);
}
}),
);
};Inside the if, TypeScript narrows event to HttpResponse, so event.status type-checks. tap passes every event along untouched, so the caller gets exactly what it would have received without the interceptor.
Logging failures too
The interceptor above logs nothing when a request fails. A failed request emits an error notification instead of a Response event. tap also accepts an observer object, so you can handle both outcomes in one place.
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.url} ok (${event.status}) ${elapsed()}ms`);
}
},
error: (error: HttpErrorResponse) => {
console.warn(`${req.method} ${req.url} failed (${error.status}) ${elapsed()}ms`);
},
}),
);
};performance.now() is a monotonic clock. It does not jump when the system clock changes, so it suits elapsed-time measurement better than Date.now().
Transforming a response
You can also change what the caller receives. Responses are immutable like requests, so use clone here too.
import { HttpEventType, HttpInterceptorFn } from '@angular/common/http';
import { map } from 'rxjs';
export const stampInterceptor: HttpInterceptorFn = (req, next) =>
next(req).pipe(
map((event) =>
event.type === HttpEventType.Response
? event.clone({ headers: event.headers.set('X-Handled-By', 'stampInterceptor') })
: event,
),
);The map returns non-response events unchanged. This is easy to forget, and the result is a broken stream.
Common mistakes
- Reading
event.statuswithout checking the type. The first event is usuallySent, which has no status. TypeScript will report this error if you skip the check. - Using
maportapfor side effects that need a response. Both run once per event, so your code can run several times for one request. - Swallowing events. If
mapreturnsundefinedfor some events, the caller never gets the response. - Logging full bodies. They can contain tokens or personal data. Log the method, URL, status, and duration.
Exercise
Why does the logging interceptor check event.type === HttpEventType.Response inside tap, and what would you add to also log requests that fail?
Show answer
next(req) emits several HttpEvent values per request, such as Sent and Response, and only the Response event has a status. The check selects it. To log failures, pass an observer object to tap with an error handler, for example tap({ next: ..., error: (e: HttpErrorResponse) => ... }), because failed requests emit an error notification and no Response event.