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
Easy- Finish
ApiKeyGuard: let a request through only when itsx-api-keyheader equalsprocess.env.API_KEY(this lesson setstasks-key-123). - Guard
POST /tasksandDELETE /tasks/:id; reading stays open. - Send
POST /taskswith a title: 403. Add the headerx-api-key: tasks-key-123and send it again: 201.GET /tasksanswers 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;
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.