angularangular-httpclientangular-ssrangular-httpclient-interceptors

Angular 17 SSR, Interceptor


Developing Angular 17 SSR applications, JWT Authentication I developed login component, and trying to get the user info from JWT. But, I'm not able to work with Interceptor & localStorage

Code for Interceptor

export const KleverInterceptor: HttpInterceptorFn = (req, next) => {

  // let token = localStorage.getItem("token");
  // console.log("Interceptor token",token);
  // const authReq = req.clone({headers : req.headers.set('Authorization',`Bearer 
  //   ${token}`)})
  console.log("interceptor");

  return next(req);
};


For understanding commented the code which Im trying to implement for httprequest
Registering app.config.ts

export const appConfig: ApplicationConfig = { 
providers: [ 
provideRouter(routes),
    provideClientHydration(),
    provideHttpClient(withFetch(), withInterceptors([NeosparkInterceptor])),
]
}

With above, im not able to invoke interceptor properly.


Solution

  • Localstorage does not support for the Server side rendering, it is a Client side feature.

    So you can use isPlatformBrowser function to check if you are running in the browser:

    import { PLATFORM_ID, Inject, Injectable } from '@angular/core';
    import { isPlatformBrowser } from '@angular/common';
    
    @Injectable({
      providedIn: 'root'
    })
    export class TokenService {
      private isBrowser: boolean;
    
      constructor(@Inject(PLATFORM_ID) private platformId: Object) {
        this.isBrowser = isPlatformBrowser(this.platformId);
      }
    
      getToken(): string | null {
        if (this.isBrowser) {
          return localStorage.getItem("token");
        }
        return null;
      }
    }
    

    Use this TokenService in the interceptor