Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Controllers and routes

A controller is a class that accepts HTTP requests and returns a response. Each of its methods is tied to an address and an HTTP method through decorators, so NestJS has no separate routes file.

Creating a controller

nest g controller posts

The CLI creates src/posts/posts.controller.ts and adds the class to the controllers of PostsModule. Write the first route:

// src/posts/posts.controller.ts
import { Controller, Get } from '@nestjs/common';
 
@Controller('posts')
export class PostsController {
  @Get()
  findAll() {
    return [
      { id: 1, title: 'First post' },
      { id: 2, title: 'Second post' },
    ];
  }
}

The string in @Controller('posts') is a prefix for every route of the class, and @Get() without an argument means "a GET request to the prefix itself". Open http://localhost:3000/posts — the browser shows the array as JSON.

HTTP methods

Each HTTP method has its own decorator, and its argument continues the address:

// src/posts/posts.controller.ts
import { Controller, Delete, Get, Patch, Post } from '@nestjs/common';
 
@Controller('posts')
export class PostsController {
  @Get()
  findAll() {
    return 'List of posts';
  }
 
  @Get('popular')
  findPopular() {
    return 'Popular posts';
  }
 
  @Post()
  create() {
    return 'Post created';
  }
 
  @Patch(':id')
  update() {
    return 'Post updated';
  }
 
  @Delete(':id')
  remove() {
    return 'Post deleted';
  }
}
DecoratorRequest
@Get()GET /posts
@Get('popular')GET /posts/popular
@Post()POST /posts
@Patch(':id')PATCH /posts/5
@Delete(':id')DELETE /posts/5

Requests other than GET cannot be sent from the browser address bar. Check them with curl:

curl -X POST http://localhost:3000/posts
curl -X DELETE http://localhost:3000/posts/5

The terminal shows Post created and Post deleted.

What you can return

  • A string — the client receives it as text.
  • An object or array — NestJS turns it into JSON and adds the Content-Type: application/json header.
  • A promise — NestJS waits for the result. That is why methods can be declared async.

The default status code is 200, and 201 for @Post(). The @HttpCode() decorator sets a different one:

// src/posts/posts.controller.ts
import { Delete, HttpCode } from '@nestjs/common';
 
@Delete(':id')
@HttpCode(204)
remove() {}

Code 204 means "success, no response body".

Common mistake

Routes of one controller are checked in the order they are declared. If @Get(':id') comes before @Get('popular'), the request /posts/popular reaches the first method and id becomes the string popular. Declare routes with fixed addresses above routes with parameters.

Thanks for reading!

Donate to the site — we work hard for you.