Menu
CoddyTech

Guards

Part of the TypeScript and NestJS section of Coddy's Node.js journey. Lesson 14 of 17.

Anyone can create or delete tasks. A guard decides whether a request may reach its handler: Nest calls its canActivate, and when it returns false, Nest answers 403 Forbidden without running the method.

@Injectable()
export class OpenHoursGuard implements CanActivate {
    canActivate(context: ExecutionContext): boolean {
        const hour = new Date().getHours();
        return hour >= 9 && hour < 17;
    }
}

@Post()
@UseGuards(OpenHoursGuard)
book() {}

context.switchToHttp().getRequest() gives the request; Node stores its header names in lower case, so read request.headers['x-api-key']. @UseGuards on a method guards that method. On the controller class it guards every method in it.

challenge icon

Challenge

Easy
  • Finish ApiKeyGuard: let a request through only when its x-api-key header equals process.env.API_KEY (this lesson sets tasks-key-123).
  • Guard POST /tasks and DELETE /tasks/:id; reading stays open.
  • Send POST /tasks with a title: 403. Add the header x-api-key: tasks-key-123 and send it again: 201. GET /tasks answers without it.

Try it yourself

import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';

@Injectable()
export class ApiKeyGuard implements CanActivate {
    canActivate(context: ExecutionContext): boolean {
        // Let the request through only when its x-api-key header
        // equals process.env.API_KEY.
        return true;
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in TypeScript and NestJS