Support Online
Skip to main content

NestJS Guards Guide: Application Security and Authorization

What will you learn in this guide?

In this guide, you will learn the NestJS Guards structure in practice.
You will use guards at the global, controller and method level.
You will learn to exempt some routes from security.

🧠 Technical Summary

The topic is authorization with NestJS Guards.
The problem is the risk of unauthorized access.
The solution is to check the requests before the controller.


Prerequisites

  • Node.js (v12 and above)
  • VS Code or similar editor
  • Postman or similar API client
  • Basic NestJS knowledge

1. Project Setup

nest new guvenlik-uygulamasi
cd guvenlik-uygulamasi
npm run start:dev
  • These commands create the NestJS project and start the development server.

2. What is Guard?

  1. Guard determines whether the request can reach the route handler.
  2. Works like a security guard.
  3. Controller decides before running.

3. Creating API Key AuthGuard

3.1 Guard File


// src/guards/api-key.guard.ts
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';

@Injectable()
export class ApiKeyGuard implements CanActivate {
canActivate(context: ExecutionContext): boolean {
const request = context.switchToHttp().getRequest();
return request.headers['x-api-key'] === 'RABISU_GIZLI_ANAHTAR';
}
}
  • This guard controls the x-api-key header.

4. Using Guard at the Controller Level


import { Controller, Get, UseGuards } from '@nestjs/common';
import { ApiKeyGuard } from './guards/api-key.guard';

@Controller()
@UseGuards(ApiKeyGuard)
export class AppController {

@Get()
getHello(): string {
return 'Korunan Alan';
}
}
  • This structure protects all routes within the controller.

5. Guard Binding Levels

5.1 Global Guard


app.useGlobalGuards(new ApiKeyGuard());
  • This structure protects the entire application.

5.2 Method Level


@Get('ozel')
@UseGuards(ApiKeyGuard)
ozelAlan() {
return 'Özel Alan';
}
  • Only the relevant endpoint is protected.

6. Multiple Guard Usage

6.1 Second Guard


// src/guards/kurumsal.guard.ts
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';

@Injectable()
export class KurumsalGuard implements CanActivate {
canActivate(context: ExecutionContext): boolean {
const request = context.switchToHttp().getRequest();
return request.headers['kurumsal-id'] === '999-RBS';
}
}
  • This guard checks corporate identity.

6.2 Combined Use


@Get('kurumsal-panel')
@UseGuards(ApiKeyGuard, KurumsalGuard)
kurumsalPanel() {
return 'Kurumsal Panel';
}

Guards work in turns.

  • If one of them fails, the request is rejected.

7. Defining a Public Route

7.1 Public Decorator


// src/decorators/public.decorator.ts
import { SetMetadata } from '@nestjs/common';

export const IS_PUBLIC_KEY = 'isPublic';
export const Public = () => SetMetadata(IS_PUBLIC_KEY, true);
  • This decorator marks the route publicly.

7.2 Control Within Guard


import { Reflector } from '@nestjs/core';

constructor(private reflector: Reflector) {}

const isPublic = this.reflector.getAllAndOverride<boolean>(
IS_PUBLIC_KEY,
[context.getHandler(), context.getClass()],
);

if (isPublic) {
return true;
}
  • This code bypasses the guard check on public routes.

7.3 Public Endpoint


@Get('herkese-acik')
@Public()
herkeseAcik() {
return 'Bu rota herkese açık';
}
  • This endpoint works without an API key.

Frequently Asked Questions

  1. What is the difference between Guard and Middleware? Middleware does not know context. Knows guard, handler and class information.

  2. Can Guard be asynchronous? Yes. Promise or Observable may be returned.

  3. Can a guard use a database? Yes. Service is injectable.

  4. Can 403 errors be customized? Yes. Exception can be thrown.

  5. Is it done with RBAC Guards? Yes. Role control is done with Guard.


Result

In this guide, you learned the NestJS Guards structure completely. You have implemented API Key, multi guard and public route scenarios. Guards are the foundation of secure NestJS applications.

You can safely use this structure on the GenixNode infrastructure.