In Angular, Auth Guards are used to protect routes from unauthorized access — a key feature when building secure applications.
Let’s break it down simply and show how to implement it 🔐
🔰 What is an Auth Guard in Angular?
An Auth Guard is a service that implements interfaces like:
CanActivate
CanActivateChild
CanLoad
CanDeactivate
Auth guards decide whether a user can or cannot access a route based on some logic — usually login status or roles.
🛡 Common Guard Types
Interface | Use Case |
---|---|
CanActivate |
Checks access before loading a route |
CanActivateChild |
Checks access for child routes |
CanLoad |
Prevents lazy-loaded modules from even being loaded |
CanDeactivate |
Confirms navigation away from the component |
🧑💻 Create an Auth Guard
1. Generate the guard
ng generate guard auth
2. Implement CanActivate
interface
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { AuthService } from './auth.service';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(): boolean {
if (this.authService.isLoggedIn()) {
return true;
} else {
this.router.navigate(['/login']);
return false;
}
}
}
auth.service.ts
might look like:
isLoggedIn(): boolean {
return !!localStorage.getItem('token');
}
🛣 Apply the Guard to Routes
In your app-routing.module.ts
:
import { AuthGuard } from './auth.guard';
const routes: Routes = [
{
path: 'dashboard',
component: DashboardComponent,
canActivate: [AuthGuard]
},
{
path: 'login',
component: LoginComponent
}
];
🧠 Bonus: CanLoad Example (Lazy Loaded Modules)
canLoad(route: Route): boolean {
return this.authService.isLoggedIn();
}
Apply it like:
{
path: 'admin',
loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule),
canLoad: [AuthGuard]
}
✅ Summary
- Auth Guards are services that protect routes.
- They use interfaces like
CanActivate
,CanLoad
, etc. - They help you redirect users to login if they're not authorized.
Happy Coding!