angularcookiesserver-side-renderingangular-ssrngx-cookie-service

How to retrieve a value from ngx-cookie-service before the app loads?


I'm encountering an issue when a user reloads the page. On app startup, there’s a brief delay (100-400ms) needed to retrieve a value from the cookie. During this time, the user is briefly redirected to the login page, but once the cookie value is retrieved, the app navigates back to the home page. I've attached my HTML and TypeScript code that seems to be causing this problem. How can I implement this: first load the cookie, then navigate to the login or home page?

// app.component.html
<div id="app-main-container" style="height: 100vh; overflow: hidden;" *ngIf="globals.isAuthenticated; else login">
  <app-side-nav></app-side-nav>
  <div class="main">
    <app-nav-bar></app-nav-bar>
    <router-outlet></router-outlet>
    <app-footer></app-footer>
  </div>
</div>

TS file - Globals

 // globals
 get isAuthenticated(): boolean {
    return !!(this.auth)
 }

 get auth() {
   if (this._auth != null) {
      return this._auth;
   } else {
      const authJson = this.cookieService.get('auth');

     if (!authJson) {
        console.warn("Auth cookie is missing");
     }
     // Attempt to parse only if loggedUserJson is not null or undefined
     const data = authJson ? JSON.parse(authJson) : null;

     if (data) {
        this._auth = data;
        return this._auth;
      } else {
       this._auth = null;
       return this._auth;
     }
   }
 }

constructor(
    private cookieService: CookieService
  ) {}

Solution

  • You may have SSR enabled, so you can try the below fix, which shows a loader when SSR loads login page and then navigates to the main page.

    The @defer shows the login page when you are in browser and the @placeholder will show a loading screen when you are in server.

    Deferrable Views - Angular.dev

    @if(isBrowser) {
       <!-- Login HTML goes here -->
    } @placeholder {
       Loading... <!-- replace with some nice spinner HTML -->
    }
    

    Also noticed that there is a ngx-cookie-service-ssr, maybe this can help with this SSR problem. Assuming you are using SSR.