Routing With Decorators

HTTP Verbs Map to Method Decorators

Routing With Decorators

Every HTTP method has a decorator. The controller prefix and method path combine into the full route.

4 min read Level 2/5 #nestjs#routing#http
What you'll learn
  • Use `@Get`, `@Post`, `@Put`, `@Patch`, and `@Delete`
  • Understand how the controller prefix and method path combine
  • Define a wildcard route

In Nest, routing is decorator-driven. The controller carries the path prefix; each method’s decorator carries the verb and the sub-path. The two combine to form the full route.

All the Verb Decorators

import {
  Controller, Get, Post, Put, Patch, Delete, Head, Options, All,
} from '@nestjs/common';

@Controller('users')
export class UsersController {
  @Get()           list()    {}     // GET    /users
  @Get(':id')      findOne() {}     // GET    /users/:id
  @Post()          create()  {}     // POST   /users
  @Put(':id')      replace() {}     // PUT    /users/:id
  @Patch(':id')    update()  {}     // PATCH  /users/:id
  @Delete(':id')   remove()  {}     // DELETE /users/:id
}

@Head, @Options, and @All exist for the less common cases. @All matches every verb — useful for proxies or “method not allowed” pages.

Path Composition

The controller path and method path concatenate with a /:

ControllerMethodFinal route
@Controller('users')@Get()GET /users
@Controller('users')@Get(':id')GET /users/:id
@Controller('users')@Get('me')GET /users/me
@Controller()@Get('health')GET /health

The empty @Controller() is fine for things like a health endpoint that doesn’t fit under a feature prefix.

Wildcards and Sub-Paths

You can use wildcards for catch-alls:

@Controller('files')
export class FilesController {
  @Get('archive/*')              // matches /files/archive/anything/at/all
  fromArchive() {}

  @Get('*')                       // catch-all inside /files
  notFound() { return 'no such file'; }
}

Order doesn’t matter — Nest picks the most specific match.

Versioning the Easy Way

setGlobalPrefix('api') plus a per-method @Version('1') decorator give you GET /api/v1/users routes without rewriting every controller. You turn versioning on once in main.ts:

import { VersioningType } from '@nestjs/common';

app.setGlobalPrefix('api');
app.enableVersioning({ type: VersioningType.URI, defaultVersion: '1' });

That’s all you need to get the basics working. The next few lessons drill into pulling values out of the request.

Route Parameters →