Angular Guard doesn't work when reloading page (v19)

Discussão em 'Angular' iniciado por Carlos Esteban Castro, Fevereiro 10, 2025.

  1. Recently I have been through some trouble with my auth guard, which calls the API to check if current user is successfully logged in sending the auth cookie. This API returns a boolean value.

    The guard works perfect when trying to access /dashboard without previously logging in, however, when I'm already navigating through the /dashboard routes, and refresh the page it asks me to login again.

    I realised that when this happens, guard isn't calling backend to check the auth. Is anyone else having the same problem?

    PD: SSR is enabled on my project

    { path: 'dashboard', component: DashboardComponent, canActivate: [authGuard], children: [ // children routes ] }

    Guard:

    export const authGuard: CanActivateFn = (route, state) => {
    const authService = inject(AuthService);
    const router = inject(Router);

    return authService.checkAuth().pipe(
    map(isAuthenticated => {
    if (!isAuthenticated) {
    router.navigate(['/login']);
    return false;
    }
    return true;
    }),
    catchError(error => {
    console.error(error);
    router.navigate(['/login']);
    return of(false);
    })
    );
    };


    Check auth method:

    checkAuth():Observable<Boolean> {
    return this.http.get<Boolean>(`${this.apiUrl}/api/v1/auth/check-auth`, {withCredentials: true}).pipe(
    catchError(this.handleError)
    );
    }


    I have already tried using CanActivateChild instead of CanActivate to see if the trouble is related to the children routers, but stil doesn't work and to be honest I'm new to Angular so I don't know what else to try...

    I could've tried to use localStorage to store a value after user is logged in, but SSR is enabled on my project.

    Continue reading...

Compartilhe esta Página