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?