NestJS

Lesson 04

Guards for auth and authorization

Use guards to approve or reject a request before protected controller code runs.

Good Code

reviews.controller.ts
import { Controller, Get, UseGuards } from "@nestjs/common";

@Controller("reviews")
@UseGuards(SessionGuard, ReviewerRoleGuard)
export class ReviewsController {
  // Guards decide access before this method runs.
  @Get("pending")
  findPending() {
    return this.reviews.findPending();
  }
}

Bad Code

reviews.controller.ts
import { Controller, Get, Req } from "@nestjs/common";

@Controller("reviews")
export class ReviewsController {
  @Get("pending")
  findPending(@Req() request: any) {
    // Access checks are mixed into route behavior.
    if (!request.user || request.user.role !== "reviewer") {
      return [];
    }
    return this.reviews.findPending();
  }
}

Review Notes

What to review

Good Code

The good version declares authentication and role checks at the controller boundary. A reviewer can see access policy before reading route behavior.

Bad Code

The bad version hides authorization inside the route method and returns an empty list on denial. That can mask a security bug as normal application behavior.

Takeaways

  • Authorization checks belong before the route body, not halfway through controller logic.