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.

HttpInterceptorFn

An interceptor for HTTP requests made via HttpClient.

See more...

      
      type HttpInterceptorFn = (req: HttpRequest<unknown>, next: HttpHandlerFn) => Observable<HttpEvent<unknown>>;
    

See also

Description

HttpInterceptorFns are middleware functions which HttpClient calls when a request is made. These functions have the opportunity to modify the outgoing request or any response that comes back, as well as block, redirect, or otherwise change the request or response semantics.

An HttpHandlerFn representing the next interceptor (or the backend which will make a real HTTP request) is provided. Most interceptors will delegate to this function, but that is not required (see HttpHandlerFn for more details).

HttpInterceptorFns are executed in an injection context. They have access to inject() via the EnvironmentInjector from which they were configured.

Further information is available in the Usage Notes...

Usage notes

Here is a noop interceptor that passes the request through without modifying it:

      
      export const noopInterceptor: HttpInterceptorFn = (req: HttpRequest<unknown>, next:
HttpHandlerFn) => {
  return next(modifiedReq);
};
    

If you want to alter a request, clone it first and modify the clone before passing it to the next() handler function.

Here is a basic interceptor that adds a bearer token to the headers

      
      export const authenticationInterceptor: HttpInterceptorFn = (req: HttpRequest<unknown>, next:
HttpHandlerFn) => {
   const userToken = 'MY_TOKEN'; const modifiedReq = req.clone({
     headers: req.headers.set('Authorization', `Bearer ${userToken}`),
   });

   return next(modifiedReq);
};