Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 42 ยท Controllers and Routing

Controllers and Routing

Learn how NestJS controllers map HTTP requests to methods: @Controller prefixes, route decorators, status codes, route order, wildcards and API versioning.

A controller is the class that receives requests and sends back responses. It should be thin: read what came in, call a service to do the actual work, return the result. Routing in Nest is declarative. Instead of calling app.get('/cats', handler), you describe the route with decorators next to the method that handles it, and Nest builds the router at startup, as you saw in How a Nest App Boots.

This lesson covers prefixes, HTTP method decorators, status codes, route ordering, wildcards and versioning. Real controller code is read-only here. For each idea there is a runnable stand-in: a small route table and dispatcher in plain JavaScript that behaves like Nest's routing for these features.

A first controller

TypeScript
import { Controller, Get, Post, Delete, Param, HttpCode } from '@nestjs/common';

@Controller('cats')
export class CatsController {
  @Get()
  findAll() {
    return [{ id: 1, name: 'Tom' }];
  }

  @Get(':id')
  findOne(@Param('id') id: string) {
    return { id: Number(id), name: 'Tom' };
  }

  @Post()
  create() {
    return { id: 2, name: 'Luna' };
  }

  @Delete(':id')
  @HttpCode(204)
  remove(@Param('id') id: string) {
    // delete it, return nothing
  }
}

The @Controller('cats') decorator sets a route prefix: every route in this class starts with /cats. Each method decorator adds the HTTP method and an optional path segment, so @Get(':id') answers GET /cats/7, and the final path is the prefix plus the segment. The decorators available are @Get, @Post, @Put, @Patch, @Delete, @Options, @Head and @All (any method).

A controller only becomes active when it is listed in the controllers array of a module, which you will see in Modules.

Anatomy of a route

Controller prefix @Controller('cats') starts every path with /cats.
Method decorator @Get(':id') adds the verb and a path segment.
Handler method The class method that runs for a match.
Return value Nest turns it into the response body.

Prefix plus segment gives the full route.

1 / 2

What the return value does

In Nest you normally return data and let the framework write the response. Objects and arrays become JSON with status 200, strings are sent as text, and promises are awaited, so an async method just works. The default status is 200 for every method except @Post(), which defaults to 201 Created. Override it with @HttpCode():

TypeScript
@Post('login')
@HttpCode(200)
login() {
  return { token: 'abc' };
}

Other helpers set headers and redirects: @Header('Cache-Control', 'no-store') adds a response header, and @Redirect('https://nestjs.com', 301) redirects. Errors are thrown as exceptions, not returned, which is the topic of Exception Filters and Errors.

A route table you can run

Decorators only record metadata. The stand-in below does the same recording with an explicit list, then dispatches requests against it. It reproduces three behaviors: the prefix joins the segment, the default status is 201 for POST and 200 otherwise, and @HttpCode(204) overrides it. Unknown routes get Nest's standard 404 body.

Node.js A decorator-style route table and dispatcher

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Route order matters

Nest registers routes in the order they appear in the class. A route with a parameter, like @Get(':id'), matches almost anything in that position, so if it comes before a fixed route such as @Get('popular'), the request GET /cats/popular is captured by :id and the fixed route never runs.

TypeScript
@Controller('cats')
export class CatsController {
  @Get('popular')   // declare fixed paths first
  popular() { /* ... */ }

  @Get(':id')       // then the catch-all style routes
  findOne(@Param('id') id: string) { /* ... */ }
}

The same applies across controllers, which are registered in module order. Keep specific routes above parameterized ones, and prefer distinct prefixes when you can.

Wildcards and API versioning

Paths can contain wildcards. Nest 11 runs on Express 5 by default, whose router requires wildcards to be named: @Get('files/*splat') matches /files/a/b/c.txt and puts the rest of the path in the parameter splat. Older Nest versions accepted a bare *, so this is one thing to check when upgrading.

Versioning lets old and new clients share one app. You turn it on in main.ts and put a version on controllers or single routes:

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

app.enableVersioning({ type: VersioningType.URI }); // /v1/cats, /v2/cats

@Controller({ path: 'cats', version: '1' })
export class CatsV1Controller { /* ... */ }

@Controller({ path: 'cats', version: '2' })
export class CatsV2Controller { /* ... */ }

URI versioning is the most common choice because it is easy to see and cache. Nest also supports header, media type and custom versioning. The stand-in below shows the difference between the first two with a tiny matcher: the URI strategy reads /v1/... from the path, the header strategy reads X-API-Version. It also tests a named wildcard.

Node.js URI versus header versioning, and a named wildcard

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Global prefix and other options

app.setGlobalPrefix('api') puts every route under /api, so GET /api/cats is the cats list. You can exclude routes, for example a health check, from the prefix. Combined with versioning, the URL becomes /api/v1/cats.

Other route helpers worth knowing:

  • @Controller({ path: 'cats', host: 'admin.example.com' }) restricts a controller to a host. It is rarely needed and has a small performance cost.
  • @All() handles every HTTP method on a path, useful for catch-all handlers.
  • Controllers can return a Promise or an RxJS Observable, and Nest waits for it.

Keep controllers boring. If a method grows past a few lines, move the logic into a provider. The next lesson shows how to read the request, and Providers and Dependency Injection shows where the real work goes.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What full route does @Controller('cats') plus @Get(':id') create?

    The controller prefix and the method path are joined with a slash, so :id is a route parameter under /cats.
  2. 2. What is the default HTTP status of a successful @Post() handler?

    POST handlers default to 201 Created. All other methods default to 200. You can change it with @HttpCode().
  3. 3. Why should @Get('popular') be declared before @Get(':id') in the same controller?

    Routes are registered in declaration order, and a parameter route matches any value in its position.
  4. 4. What does app.enableVersioning({ type: VersioningType.URI }) change?

    With URI versioning the version appears in the path, and each controller or route picks its version in the decorator options.

Summary

  • A controller is a class that maps requests to methods through @Controller() and HTTP method decorators; it must be listed in a module.
  • The full route is the controller prefix plus the method path; app.setGlobalPrefix() adds a prefix to all of them.
  • Return values become the response; POST defaults to 201, other methods to 200, and @HttpCode() overrides it.
  • Routes match in declaration order, so declare fixed paths before parameter routes.
  • Wildcards must be named on Nest 11 (Express 5), such as files/*splat.
  • Versioning (URI, header, media type or custom) lets several API versions live in one app.
  • The stand-ins use an explicit route table; real Nest builds the same table from decorator metadata.

Next: Reading Request Data