0
0
AngularHow-ToBeginner · 4 min read

How to Add Auth Token Using Interceptor in Angular

In Angular, you add an auth token to HTTP requests by creating an HttpInterceptor that modifies outgoing requests to include the token in the Authorization header. Then, register this interceptor in the providers array of your module to apply it globally.
📐

Syntax

An Angular HttpInterceptor is a class that implements the HttpInterceptor interface and overrides the intercept method. This method receives the outgoing HttpRequest and the HttpHandler. You clone the request to add the auth token in the headers, then pass it to next.handle() to continue the request chain.

  • intercept(req, next): Method to modify the request.
  • req.clone(): Creates a copy of the request with new headers.
  • Authorization header: Where the token is added, usually as Bearer <token>.
typescript
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const token = 'your-auth-token';
    const authReq = req.clone({
      setHeaders: {
        Authorization: `Bearer ${token}`
      }
    });
    return next.handle(authReq);
  }
}
💻

Example

This example shows a complete Angular interceptor that adds a static auth token to all HTTP requests. It also shows how to register the interceptor in the app module so Angular uses it automatically.

typescript
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HTTP_INTERCEPTORS } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const token = 'abc123token';
    const authReq = req.clone({
      setHeaders: {
        Authorization: `Bearer ${token}`
      }
    });
    return next.handle(authReq);
  }
}

// In your app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, HttpClientModule],
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}
Output
All outgoing HTTP requests include the header: Authorization: Bearer abc123token
⚠️

Common Pitfalls

  • Forgetting to add multi: true when providing the interceptor causes Angular to overwrite other interceptors.
  • Not cloning the request before modifying headers will cause errors because requests are immutable.
  • Hardcoding tokens is insecure; use a service to get the current token dynamically.
  • Interceptor runs for all HTTP requests, including those that may not need auth; consider filtering URLs if needed.
typescript
/* Wrong: Modifying request directly without clone */
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  // req.headers.set('Authorization', `Bearer token`); // Error: headers are immutable
  return next.handle(req);
}

/* Right: Clone request before setting headers */
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  const authReq = req.clone({ setHeaders: { Authorization: `Bearer token` } });
  return next.handle(authReq);
}
📊

Quick Reference

  • HttpInterceptor: Interface to implement for intercepting HTTP requests.
  • intercept(): Method to modify requests.
  • req.clone(): Use to add headers safely.
  • Authorization header: Standard header to send auth tokens.
  • multi: true: Required when providing interceptors to keep multiple interceptors.

Key Takeaways

Create an HttpInterceptor class and implement the intercept method to add the auth token.
Always clone the HttpRequest before modifying headers to avoid errors.
Register the interceptor in the providers array with multi: true to enable multiple interceptors.
Use the Authorization header with the Bearer scheme to send tokens.
Avoid hardcoding tokens; retrieve them dynamically from a secure service.