typescript 49 lines · 5 steps

Functional route guards in Angular

Two CanActivateFn guards gate routes on auth state and user roles, redirecting via UrlTree when access is denied.

Explained by highlit
1import { inject } from '@angular/core';
2import {
3 CanActivateFn,
4 Router,
5 ActivatedRouteSnapshot,
6 RouterStateSnapshot,
7} from '@angular/router';
8import { map, take } from 'rxjs/operators';
9 
10import { AuthService } from '../services/auth.service';
11 
12export const authGuard: CanActivateFn = (
13 route: ActivatedRouteSnapshot,
14 state: RouterStateSnapshot,
15) => {
16 const auth = inject(AuthService);
17 const router = inject(Router);
18 
19 return auth.isAuthenticated$.pipe(
20 take(1),
21 map((isAuthenticated) => {
22 if (isAuthenticated) {
23 return true;
24 }
25 
26 return router.createUrlTree(['/login'], {
27 queryParams: { returnUrl: state.url },
28 });
29 }),
30 );
31};
32 
33export const roleGuard = (...allowedRoles: string[]): CanActivateFn => {
34 return () => {
35 const auth = inject(AuthService);
36 const router = inject(Router);
37 
38 return auth.currentUser$.pipe(
39 take(1),
40 map((user) => {
41 if (user && allowedRoles.includes(user.role)) {
42 return true;
43 }
44 
45 return router.createUrlTree(['/forbidden']);
46 }),
47 );
48 };
49};
01 / 01
STEP 01

Walkthrough

Space play ←→ step click any line
Three takeaways
  1. 1Functional guards use inject() to grab dependencies without a class or constructor.
  2. 2Returning a UrlTree from a guard performs a redirect instead of a plain block.
  3. 3Wrapping a guard in a factory lets you parameterize it, like passing allowed roles.

Related explainers

typescript
import { registerLocaleData } from '@angular/common';
import localeFr from '@angular/common/locales/fr';
import localeFrExtra from '@angular/common/locales/extra/fr';
import localeDe from '@angular/common/locales/de';

Locale-aware bootstrapping in Angular

i18n localization dependency-injection
Intermediate 8 steps
typescript
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import * as Joi from 'joi';
 

Validating env config at boot in NestJS

configuration schema-validation environment-variables
Intermediate 8 steps
java
@Component
@Converter
public class EncryptedStringConverter implements AttributeConverter<String, String> {
 

Transparent column encryption in Spring & JPA

encryption aes-gcm jpa-converter
Advanced 10 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Cache } from 'cache-manager';
import { InjectRepository } from '@nestjs/typeorm';

A cache-aside country lookup in NestJS

cache-aside dependency-injection batch-lookup
Intermediate 8 steps
php
<?php
 
namespace App\Services;
 

How a password strength validator works in PHP

validation regular-expressions data-driven
Intermediate 8 steps
java
package com.acme.billing.config;
 
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;

Feature-flagged beans with Spring @ConditionalOnProperty

feature-flags conditional-beans strategy-pattern
Intermediate 5 steps

Share this explainer

Here's the card — post it anywhere.

Functional route guards in Angular — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code