Skip to main content

Overview

The authGuard is a functional route guard that checks if a user is authenticated before allowing access to protected routes. If the user is not authenticated, they are redirected to the login page.

Type signature

export const authGuard: CanActivateFn
CanActivateFn
() => boolean | UrlTree
Angular’s functional guard type that returns true to allow navigation or a UrlTree to redirect

How it works

The auth guard follows this logic:
  1. Security open check: If environment.securityOpen is true, all routes are accessible without authentication
  2. Authentication check: Injects AuthStore and checks if the user is authenticated via isAuthenticated()
  3. Redirect: If not authenticated, creates a URL tree to redirect to /auth/login

Configuration

environment.securityOpen
boolean
When set to true, bypasses authentication checks for all routes. Useful for development or testing.

Usage

Apply the guard to routes in your route configuration:
import { Routes } from '@angular/router';
import { authGuard } from '@core/providers/auth.guard';

export const routes: Routes = [
  {
    path: 'dashboard',
    component: DashboardComponent,
    canActivate: [authGuard]
  },
  {
    path: 'profile',
    component: ProfileComponent,
    canActivate: [authGuard]
  }
];

Source code

import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { environment } from '@env/environment';
import { AuthStore } from '@services/state/auth.store';

/**
 * Guard function to check if the user is authenticated.
 * @returns True if the user is authenticated. Otherwise the URL tree to redirect to the login page.
 */
export const authGuard: CanActivateFn = () => {
  if (environment.securityOpen) return true;
  const authStore = inject(AuthStore);
  if (authStore.isAuthenticated()) return true;
  const router = inject(Router);
  return router.createUrlTree(['/auth', 'login']);
};

Dependencies

  • AuthStore - Provides authentication state and the isAuthenticated() method
  • Router - Creates navigation URL trees for redirects
  • environment.securityOpen - Configuration flag to bypass authentication

Build docs developers (and LLMs) love