0

Hello, I have 3 different apis for different services. Each API has you own Auth Token. I want to create 3 http interceptors, one for each api. I know create a httpInterceptor for all project, but how I can create a different interceptor for each api service?

1 Answer 1

1

You can use a single interceptor, and since in this one you have access to read the URL, you can create a function that depending on this uses a different token, for example:

        intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
          let token;
          
          if (request.url.indexOf(PATH_ROUTE_ONE) !== -1) {
            token =  localStorage.getItem(TK1);
          } else if(request.url.indexOf(PATH_ROUTE_TWO) !== -1) {
            token =  localStorage.getItem(TK2);
          } else {
            token =  localStorage.getItem(TK3);
          }

          if (token) {
            request = request.clone({
              setHeaders: {
                authorization: `Bearer ${token}`,
              },
            });
          }

          return next.handle(request).pipe(
            tap((res) => {
              if (res instanceof HttpResponse) {
                // TODO: Update token info
              }
            }),
            catchError((err: HttpErrorResponse) => throwError(err)),
          );
        }

If you want to use 3 paths you can do the same and you only read the URL to know if you apply it or let it continue long

       intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
          let token = localStorage.getItem(TK1)
          
          if (request.url.indexOf(PATH_ROUTE_ONE) !== -1) {
            request = request.clone({
              setHeaders: {
                authorization: `Bearer ${token}`,
              },
            });
          }

          return next.handle(request).pipe(
            tap((res) => {
              if (res instanceof HttpResponse) {
                // TODO: Update token info
              }
            }),
            catchError((err: HttpErrorResponse) => throwError(err)),
          );
        }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.