2

I'm working on an Angular 17 project with login and session functionality. Everything is working well except for the guard. Every time I refresh the page, the screen briefly blinks back to the login screen and then returns to the current page.

This issue happens because, in the SSR application, the guard does not have access to the login session when the page is being generated.

I migrated to ngx-cookie-service-ssr to store the session information, and I used the SSR configuration. However, the issue still persists. Even if you check the example project from this library (https://github.com/pj-labs/angular-ssr-docker), it has the same problem.

The only thing that temporarily solved the issue was the following code:

@Injectable({
    providedIn: 'root'
})
export class AuthGuard {

    constructor(private loginService: LoginService,  
                @Inject(PLATFORM_ID) private platformId: Object) { }

    canActivate(): boolean {   
        if (isPlatformBrowser(this.platformId)) {
            if (this.loginService.isLoggedIn() && !this.loginService.isTokenExpired()) {
                return true;
            }else{
                this.loginService.logout();
            }
            return false;
        }
        return true;
    }
}

I don’t consider this code safe since it always evaluates to true if the page is not built.

Does anyone know how to solve this problem?

2 Answers 2

1

This is a known issue in DEV server, when using ngx-cookie-service-ssr, when you start the actual SSR server, this issue will not happen. If you find this an inconvenience.

The below approach, does not do SSR, for the login page but you can show a spinner to temporarily show until the proper screen loads after guard.

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

It is also a good idea to create a issue ticket on their github page, since this issue happens only on the browser.

Sign up to request clarification or add additional context in comments.

Comments

0

As far as I know, the main approach is either to avoid authentication control for server-side rendered pages or, if you use it, ensure that it returns false for SSR. Alternatively, using the cookie trick with ngx-cookie-service + ngx-cookie-service-ssr should logically be sufficient, even if you say otherwise. I haven’t tried it myself, so I can’t guarantee that it works, but it should work as the general flow(not cookie one) is well-explained here:

The Flow

By the way, this is a late response. You’ve probably already figured out the solution, but I’d appreciate hearing how you approached it.

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.