DEV Community

process20
process20

Posted on

Implementing the interceptors

Hi,
I have a problem with interceptors, now I'm learning JWT reaching the step dealing with interceptors, I'm not able to know the source of the issue, the interceptor is getting block the login API to be consumed and generate the token that will be injected in request header in the interceptor; here the code of the interceptor class:

import { catchError } from 'rxjs/operators';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse } from "@angular/common/http";
import { Injectable } from '@angular/core';
import { tap } from 'rxjs/operators';
import { Router } from "@angular/router";
import { Observable, throwError } from 'rxjs';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

constructor(){}

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>{
      console.log("you are in interceptor");
      // get the token from the local storage
      const token = localStorage.getItem('token');
      if(token){
        console.log("token stored to the local store: "+token);
        // modify the request header
        req = req.clone({
          setHeaders: {Authorization: `${token}`}
        });
        // handling errors
        return next.handle(req).pipe(catchError(err=>{
          console.log("something wrong in interceptor");
          if(err instanceof HttpErrorResponse){
             console.log(err.status + ': token expired, login again');
          }
          return throwError(()=> new Error('Some Unknown Error'));
        }));
      }
      else console.log("token not provided");

}
Enter fullscreen mode Exit fullscreen mode

}

if you would like the full code using Node.js and angular, here is the link on angular: https://github.com/process20/JWT-Implementation.
Hope you to help me fixing this issue, I'm struggling for more than 10 days.

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay