Advanced Routing & Security
7 min read
Advanced Routing & Security
Subtopic: Lazy Loading, Guards, and Resolvers
Hello and welcome to the advanced sector of Angular routing. π
In the previous sections, you likely set up basic routes to navigate between components. Now, we will treat routing not just as a map, but as a sophisticated traffic control system. We will optimize performance by loading code only when needed, secure our application by controlling access, prevent data loss, and ensure data is ready before a user sees a page.
1. Lazy Loading Routes to Reduce Initial Bundle Size
Definition:
Lazy loading is a design pattern where modules or components are loaded asynchronously on demand, rather than all at once during the initial application load (Eager Loading).
The Problem:
Imagine an application with 50 different pages (Admin panel, User settings, Dashboards, Reports). If you use standard routing, the browser downloads the code for all 50 pages the moment the user opens the homepage. This increases the "Initial Bundle Size," leading to slow load times and a poor user experience, especially on mobile networks.
The Solution:
We split the application into smaller "chunks." The main bundle contains only what is necessary to start the app (e.g., the Header, Sidebar, and Homepage). The other pages (chunks) are downloaded from the server only when the user clicks a link to navigate to them.
Implementation (Standalone Components):
Modern Angular (v15+) uses Standalone Components, which makes lazy loading significantly cleaner than the old NgModule approach. We use the loadComponent property instead of component.
π File: app.routes.ts
import { Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
export const routes: Routes = [
// Eager loaded route (loaded immediately)
{
path: '',
component: HomeComponent,
},
// Lazy loaded route
{
path: 'admin',
// The import function returns a Promise
loadComponent: () =>
import('./admin/admin-dashboard/admin-dashboard.component')
.then(m => m.AdminDashboardComponent)
},
// Lazy loading a set of child routes
{
path: 'settings',
loadChildren: () =>
import('./settings/settings.routes')
.then(m => m.SETTINGS_ROUTES)
}
];What is happening here?
import(...): This is a dynamic import syntax. Webpack (or your builder) sees this and automatically creates a separate JavaScript file (e.g.,src_app_admin...js).- Network Request: When the user navigates to
/admin, you will see a new network request in your browser's DevTools as it fetches that specific chunk.
π‘ Did you know?
Large enterprise applications can easily exceed 5MB in bundle size. Lazy loading can reduce the initial load to under 200KB, making the app Interactive in milliseconds rather than seconds.
2. Protecting Routes: Route Guards (CanActivate / CanMatch)
Definition:
Route Guards are interfaces or functions that logic controls whether a router request should be allowed or denied. They act as checkpoints.
The Problem:
You have an /admin route. You don't want a regular user (or a non-logged-in user) to access it just by typing the URL in the browser bar.
A. CanActivate (The Standard Gatekeeper)
CanActivate decides if a route can be activated. If it returns false, navigation stops.
Modern Syntax (Functional Guards):
Class-based guards are deprecated. We now use simple functions.
π File: auth.guard.ts
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { AuthService } from './auth.service';
export const authGuard: CanActivateFn = (route, state) => {
const authService = inject(AuthService);
const router = inject(Router);
if (authService.isLoggedIn()) {
return true; // Navigation allowed
} else {
// Redirect to login page
return router.parseUrl('/login');
}
};Usage in Routes:
{
path: 'dashboard',
loadComponent: () => ...,
canActivate: [authGuard] // Array of guards
}B. CanMatch (The Route Switcher)
CanMatch controls whether the Router even sees a route as a match.
Difference between CanActivate and CanMatch:
- CanActivate: The router matches the URL, then checks permission. If denied, it throws an error or redirects. The URL is "taken."
- CanMatch: The router checks permission before matching. If denied, the router behaves as if that route configuration doesn't exist and keeps looking for other routes that match the URL.
Use Case:
You can have two routes with the same path but different components, controlled by CanMatch.
export const routes: Routes = [
{
path: 'dashboard',
canMatch: [isAdminGuard], // If admin, load AdminDashboard
loadComponent: () => import('./admin/dashboard.component')...
},
{
path: 'dashboard',
canMatch: [isUserGuard], // If regular user, load UserDashboard
loadComponent: () => import('./user/dashboard.component')...
}
];This allows you to serve completely different features to different users at the exact same URL (/dashboard).
3. Preventing Unsaved Changes: CanDeactivate Guards
Definition:CanDeactivate is a guard that runs when a user tries to leave a route.
The Problem:
A user fills out a long form but accidentally clicks "Home" or hits the "Back" button without saving. All data is lost.
The Solution:
We ask the component if it is "safe" to leave. If the component says "no" (has unsaved changes), we prompt the user for confirmation.
Step 1: Create an Interface
This ensures any component we want to protect has a standard method to check.
// can-deactivate.interface.ts
import { Observable } from 'rxjs';
export interface CanComponentDeactivate {
canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;
}Step 2: The Functional Guard
// unsaved-changes.guard.ts
import { CanDeactivateFn } from '@angular/router';
import { CanComponentDeactivate } from './can-deactivate.interface';
export const unsavedChangesGuard: CanDeactivateFn<CanComponentDeactivate> =
(component: CanComponentDeactivate) => {
// If the component has a canDeactivate method, call it.
// Otherwise, assume it's safe to leave (return true).
return component.canDeactivate ? component.canDeactivate() : true;
};Step 3: Implement in Component
// profile-edit.component.ts
export class ProfileEditComponent implements CanComponentDeactivate {
isDirty = false; // Set to true when user types in form
canDeactivate() {
if (this.isDirty) {
return confirm('You have unsaved changes. Discard and leave?');
}
return true;
}
}Step 4: Apply to Route
{
path: 'edit-profile',
component: ProfileEditComponent,
canDeactivate: [unsavedChangesGuard]
}4. Pre-fetching Data: Route Resolvers
Definition:
A Resolver is a function that fetches data during the navigation but before the component loads.
The Problem:
When a user navigates to a "Product Details" page, the component loads immediately, displaying an empty template or a "Loading..." spinner while it fetches data from the API. This can cause layout shifts (CLS) and feels "janky."
The Solution:
The Router waits for the Resolver to finish fetching data. Once the data is ready, the Router activates the component and hands it the data immediately. The component renders with content already present.
Implementation (Functional Resolver):
π File: user.resolver.ts
import { ResolveFn } from '@angular/router';
import { inject } from '@angular/core';
import { UserService } from './user.service';
import { User } from './user.model';
export const userResolver: ResolveFn<User> = (route, state) => {
const userService = inject(UserService);
const userId = route.paramMap.get('id')!;
// The router will subscribe to this Observable and wait for it to complete
return userService.getUserById(userId);
};Usage in Routes:
{
path: 'user/:id',
component: UserProfileComponent,
resolve: {
userData: userResolver // The key 'userData' holds the result
}
}Accessing Data in Component:
You can access the resolved data via ActivatedRoute or, more conveniently, using Component Input Binding (enabled in app.config.ts via withComponentInputBinding()).
// user-profile.component.ts
@Component({ ... })
export class UserProfileComponent {
// The input name matches the resolve key in the route config
@Input() userData!: User;
ngOnInit() {
console.log('Data is already here:', this.userData);
}
}β οΈ Industry Practice:
Resolvers are great, but be careful. If your API is slow, the navigation will appear "frozen" because the Router is waiting for the data. Always consider showing a global loading bar (like YouTube's red top bar) during navigation events (NavigationStart/NavigationEnd) so the user knows something is happening.
Summary
- Lazy Loading: Use
loadComponentto split your app into small chunks. - CanActivate: Checks if a user can enter a room.
- CanMatch: Checks if the room even exists for that user.
- CanDeactivate: Asks "Are you sure?" before leaving.
- Resolvers: Buys the groceries before you start cooking (pre-fetches data).
π References & Further Reading
Challenge
Challenge: Implement Advanced Application Routing
You are tasked with setting up the advanced routing configuration for an application. Your goal is to complete the appRoutes constant and implement the logic for several functional guards and a resolver using modern Angular syntax.
All necessary services and component placeholders are provided. You must only fill in the logic for the guards, the resolver, and the appRoutes array.
Requirements:
Implement
adminDashboardGuard(CanMatchFn): This guard should use the injectedAuthServiceto check if the user is an admin. It should returntrueonly ifauthService.isAdminUseris true.Implement
authGuard(CanActivateFn): This guard should protect routes that require authentication. Use the injectedAuthServiceandRouter. If the user is logged in (authService.isLoggedInis true), allow access. If not, prevent access and return aUrlTreethat redirects the user to the/loginpath.Implement
unsavedChangesGuard(CanDeactivateFn): This guard should check if the component being deactivated has ancanDeactivatemethod. If it does, it should call that method to determine if navigation should be allowed. Otherwise, it should allow navigation by default.Implement
userResolver(ResolveFn): This resolver must fetch user data before the associated route is activated. It should inject theDataServiceand use theroute.paramMap.get('id')to get the user ID from the URL, then calldataService.getUser()with that ID.Configure
appRoutes:- Root Path (
''): Redirect to/homewithpathMatch: 'full'. /home: Eagerly load theHomeComponent./login: Eagerly load theLoginComponent./dashboard: This path must have two route configurations:- The first should match only if
adminDashboardGuardreturns true, loading theAdminDashboardComponent. - The second should be a fallback for any other user, loading the
UserDashboardComponent.
- The first should match only if
/profile/:id: Load theUserProfileComponentand use theuserResolverto pre-fetch and assign data to a route data property nameduser./profile/edit: Load theEditProfileComponentand protect it with theunsavedChangesGuard./admin: This entire section must be lazy-loaded. UseloadChildrenand a dynamicimport()statement to a fictional./admin.routesfile. The entire lazy-loaded module should be protected by theauthGuard.
- Root Path (
Expected result
The correctly implemented code will define the logic for all guards and the resolver, and then use them to construct the appRoutes array according to the requirements.
Completed Guards and Resolver
// 1. Implement the canMatch guard for the admin dashboard
const adminDashboardGuard: CanMatchFn = (route, segments) => {
return inject(AuthService).isAdminUser;
};
// 2. Implement the canActivate guard for protected areas
const authGuard: CanActivateFn = (route, state) => {
const authService = inject(AuthService);
const router = inject(Router);
if (authService.isLoggedIn) {
return true;
}
return router.createUrlTree(['/login']);
};
// 3. Implement the canDeactivate guard for components with unsaved changes
const unsavedChangesGuard: CanDeactivateFn<CanComponentDeactivate> = (component, currentRoute, currentState, nextState) => {
return component.canDeactivate ? component.canDeactivate() : true;
};
// 4. Implement the resolver to pre-fetch user data
const userResolver: ResolveFn<{ id: string, name: string }> = (route, state) => {
const dataService = inject(DataService);
const userId = route.paramMap.get('id')!;
return dataService.getUser(userId);
};Completed Route Configuration
export const appRoutes: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'login', component: LoginComponent },
{
path: 'dashboard',
canMatch: [adminDashboardGuard],
component: AdminDashboardComponent
},
{
path: 'dashboard',
component: UserDashboardComponent
},
{
path: 'profile/edit',
component: EditProfileComponent,
canDeactivate: [unsavedChangesGuard]
},
{
path: 'profile/:id',
component: UserProfileComponent,
resolve: {
user: userResolver
}
},
{
path: 'admin',
canActivate: [authGuard],
loadChildren: () => import('./admin.routes').then(m => m.ADMIN_ROUTES)
}
];This solution correctly uses canMatch to provide conditional routing on the same path, canActivate to protect an entire lazy-loaded module, canDeactivate to guard a specific component route, and a resolve property to pre-fetch data before component instantiation.