Angular SSR website redirects to login page before going to actual path

Viewed 174

I use Angular SSR and when I refresh on the pages, it goes to the login page first and then to the desired page.

I also use cookies to store tokens.

canActivate( route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
return this.tokenService.isAuthenticated$.pipe(
  map(isAuth => {
   if (!isAuth) {
     this.router.navigate(['auth']).then();
     return false;
   }
   return true;
  })
);

}

const routes: Routes =  [
{
  path: 'auth',
  canActivate: [AuthGuard],
  loadChildren: () => import('./main/auth/auth.module').then(m => m.AuthModule)
},
{
  path: '', resolve: {mainInfo: MainResolverService}, component: MainComponent, children: [
    {path: '', redirectTo: 'home', pathMatch: 'full'},
    {path: 'home', loadChildren: () => import('./main/modules/global/home/home.module').then(m => m.HomeModule)},
    {path: 'faq', loadChildren: () => import('./main/modules/global/faq/faq.module').then(m => m.FaqModule)},
    {path: 'cooperation-request', loadChildren: () => import('./main/modules/global/cooperation-request/cooperation-request-module').then(m => m.CooperationRequestModule)},
    {path: 'contact-us', loadChildren: () => import('./main/modules/global/contact-us/contact-us.module').then(m => m.ContactUsModule)},
    {path: 'mentors', loadChildren: () => import('./main/modules/global/mentors/mentors.module').then(m => m.MentorsModule)},
    {path: 'category', loadChildren: () => import('./main/modules/global/category/category.module').then(m => m.CategoryModule)},
    {path: 'about', loadChildren: () => import('./main/modules/global/about/about.module').then(m => m.AboutModule)},
    {path: 'webinar/:id/:title', loadChildren: () => import('./main/modules/global/webinar/webinar.module').then(m => m.WebinarModule)},
    {path: 'user', canActivate: [AuthenticatedGuard], loadChildren: () => import('./main/modules/secured/user.module').then(m => m.UserModule)},
  ]
}

];

1 Answers

This is because the API is called on the browser and the API must be called in Express js. You can call cookies in Express through the cookie-parser package.

var express = require('express');
var cookieParser = require('cookie-parser');
var app = express();
app.use(cookieParser());
Related