Cookies concent notice

This site uses cookies from Google to deliver its services and to analyze traffic.
Learn more
Skip to main content
This site is no longer updated.Head to Angular.devHome
/

This is the archived documentation for Angular v17. Please visit angular.dev to see this page for the current version of Angular.

HTTP - Pass metadata to interceptors

Many interceptors require or benefit from configuration. Consider an interceptor that retries failed requests. By default, the interceptor might retry a request three times, but you might want to override this retry count for particularly error-prone or sensitive requests.

HttpClient requests contain a context that can carry metadata about the request. This context is available for interceptors to read or modify, though it is not transmitted to the backend server when the request is sent. This lets applications or other interceptors tag requests with configuration parameters, such as how many times to retry a request.

Create a context token

Angular stores and retrieves a value in the context using an HttpContextToken. You can create a context token using the new operator, as in the following example:

creating a context token
      
      export const RETRY_COUNT = new HttpContextToken(() => 3);
    

The lambda function () => 3 passed during the creation of the HttpContextToken serves two purposes:

  1. It lets TypeScript infer the type of this token: HttpContextToken<number> The request context is type-safe —reading a token from a request's context returns a value of the appropriate type.

  2. It sets the default value for the token. This is the value that the request context returns if no other value was set for this token. Using a default value avoids the need to check if a particular value is set.

Set context values when making a request

When making a request, you can provide an HttpContext instance, in which you have already set the context values.

setting context values
      
      this.httpClient
    .get('/data/feed', {
      context: new HttpContext().set(RETRY_COUNT, 5),
    })
    .subscribe(results => {/* ... */});
    

Read context values in an interceptor

Within an interceptor, you can read the value of a token in a given request's context with HttpContext.get(). If you have not explicitly set a value for the token, Angular returns the default value specified in the token.

reading context values in an interceptor
      
      import {retry} from 'rxjs';

export class RetryInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const retryCount = req.context.get(RETRY_COUNT);

    return next.handle(req).pipe(
        // Retry the request a configurable number of times.
        retry(retryCount),
    );
  }
}
    

Contexts are mutable

Unlike most other aspects of HttpRequest instances, the request context is mutable and persists across other immutable transformations of the request. This lets interceptors coordinate operations through the context. For instance, the RetryInterceptor example could use a second context token to track how many errors occur during the execution of a given request:

coordinating operations through the context
      
      import {retry, tap} from 'rxjs/operators';
export const RETRY_COUNT = new HttpContextToken(() => 3);
export const ERROR_COUNT = new HttpContextToken(() => 0);

export class RetryInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const retryCount = req.context.get(RETRY_COUNT);

    return next.handle(req).pipe(
        tap({
              // An error has occurred, so increment this request's ERROR_COUNT.
             error: () => req.context.set(ERROR_COUNT, req.context.get(ERROR_COUNT) + 1)
            }),
        // Retry the request a configurable number of times.
        retry(retryCount),
    );
  }
}
    
Last reviewed on Tue Nov 15 2022