Learn NestJS · 3/14

Routing and Data Flow

7 min read

NestJS: Routing and Data Flow 🚗

Welcome back! So, you've got your NestJS application up and running. Fantastic! 🥳 Now, let's talk about how it handles incoming requests and sends back responses. Think of your app as a bustling city. You need roads (routes) to guide traffic (data) to the right destinations (your logic). This guide will be your GPS for navigating the world of routing and data flow in NestJS.


1. Route Parameters and Query Strings: The Art of Asking Nicely 🗣️

The Problem: Imagine you're building a feature to get user information. You could have a route like /users/1 or /users/2. How do you tell your application that 1 and 2 are not fixed parts of the path but are actually user IDs? Also, what if you want to filter or sort data, like getting all users from a specific city? You need a way to pass this extra information in the URL.

The Solution: NestJS, building on top of Express, gives us two primary ways to handle dynamic information in a URL: Route Parameters and Query Strings.

Route Parameters (@Param())

Route parameters are used to capture values at a specific position in the URL. They are perfect for when a piece of data is a mandatory part of the path.

Let's say you have a controller that handles requests for users. To get a specific user by their ID, you can define a route like this:

typescript
// src/users/users.controller.ts
import { Controller, Get, Param } from '@nestjs/common';

@Controller('users')
export class UsersController {
  @Get(':id')
  findOne(@Param('id') id: string) {
    return `This action returns a #${id} user`;
  }
}

In the @Get(':id') decorator, the colon : tells NestJS that id is a placeholder. When a request comes in for /users/123, NestJS will capture 123 and, thanks to the @Param('id') decorator, make it available in your findOne method as the id parameter.

Under the Hood: NestJS uses the path-to-regexp library, the same one Express uses, to match incoming request URLs against the route paths you've defined. It's incredibly efficient at parsing these dynamic segments.

Query Strings (@Query())

Query strings are used for optional parameters or for filtering and sorting data. They appear at the end of the URL after a question mark ?.

Imagine you want to get a list of users, but you also want to be able to sort them and limit the number of results. Your URL might look like /users?sortBy=name&limit=10.

Here's how you'd handle that in your controller:

typescript
// src/users/users.controller.ts
import { Controller, Get, Query } from '@nestjs/common';

@Controller('users')
export class UsersController {
  @Get()
  findAll(@Query('sortBy') sortBy: string, @Query('limit') limit: string) {
    return `This action returns all users, sorted by ${sortBy} with a limit of ${limit}.`;
  }
}

With the @Query() decorator, you can easily access these optional parameters. If a query parameter isn't provided in the URL, its value will be undefined. You can then build your logic to handle these cases.

Industry Practice: It's a common practice to create a dedicated DTO (we'll cover this soon!) for your query parameters to keep your method signatures clean and your validation in one place.


2. Request Body and Payloads: Sending the Goods 📦

The Problem: So far, we've only dealt with getting data. But what about creating or updating information? For that, the client needs to send data to the server. How does our NestJS application receive and understand this data?

The Solution: For POST, PUT, and PATCH requests, data is typically sent in the request body, often in JSON format. NestJS provides the @Body() decorator to effortlessly access this incoming data.

Let's imagine you're creating a new user. The client will send a POST request to /users with the user's details in the request body.

typescript
// src/users/users.controller.ts
import { Controller, Post, Body } from '@nestjs/common';

@Controller('users')
export class UsersController {
  @Post()
  create(@Body() createUserDto: any) {
    return 'This action adds a new user';
  }
}

When a POST request with a JSON body like { "name": "John Doe", "email": "[email protected]" } is sent to /users, the @Body() decorator will parse the JSON and inject it into the createUserDto parameter.

A Funny Exaggeration: Without @Body(), you'd be like a detective trying to piece together a message from shredded paper. It's possible, but why would you do that to yourself?


3. Data Transfer Objects (DTOs): Defining the Contract 📜

The Problem: In the previous example, we used any as the type for our createUserDto. This is like inviting a stranger into your house without knowing who they are or what they want. It's risky and can lead to unexpected behavior. We need a way to define the exact shape of the data we expect.

The Solution: This is where Data Transfer Objects (DTOs) come in. A DTO is a simple class that defines the structure of data being sent over the network. By using DTOs, you get strong typing and can easily add validation.

Let's create a DTO for creating a new user.

typescript
// src/users/dto/create-user.dto.ts
export class CreateUserDto {
  name: string;
  email: string;
}

Now, we can use this DTO in our controller:

typescript
// src/users/users.controller.ts
import { Controller, Post, Body } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';

@Controller('users')
export class UsersController {
  @Post()
  create(@Body() createUserDto: CreateUserDto) {
    return `Creating user with name: ${createUserDto.name} and email: ${createUserDto.email}`;
  }
}

Now our create method knows exactly what to expect. This improves code readability and maintainability.

The Real Power: The true magic happens when you combine DTOs with validation pipes. NestJS has a built-in ValidationPipe that works with popular libraries like class-validator and class-transformer. This allows you to add decorators to your DTOs to enforce validation rules.

Here's an enhanced CreateUserDto:

typescript
// src/users/dto/create-user.dto.ts
import { IsString, IsEmail } from 'class-validator';

export class CreateUserDto {
  @IsString()
  name: string;

  @IsEmail()
  email: string;
}

To enable this, you need to set up the ValidationPipe globally in your main.ts:

typescript
// src/main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe } from '@nestjs/common';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(new ValidationPipe());
  await app.listen(3000);
}
bootstrap();

Now, if a request comes in with a missing name or an invalid email, NestJS will automatically send back a 400 Bad Request response with a detailed error message. How cool is that? ✨


4. Status Codes and Response Headers: Setting the Right Tone 🎭

The Problem: By default, NestJS sends a 200 OK status code for successful GET requests and 201 Created for POST requests. But what if you want to send a different status code? Or what if you need to add custom headers to your response?

The Solution: NestJS provides decorators to easily manage status codes and headers.

Status Codes (@HttpCode())

The @HttpCode() decorator allows you to specify the HTTP status code that should be returned.

typescript
// src/users/users.controller.ts
import { Controller, Post, HttpCode } from '@nestjs/common';

@Controller('users')
export class UsersController {
  @Post()
  @HttpCode(204)
  create() {
    // some logic to create a user
    return; // No content is returned
  }
}

In this example, a successful POST request to /users will now return a 204 No Content status code.

Response Headers (@Header())

The @Header() decorator lets you add custom headers to the response.

typescript
// src/users/users.controller.ts
import { Controller, Get, Header } from '@nestjs/common';

@Controller('users')
export class UsersController {
  @Get()
  @Header('Cache-Control', 'none')
  findAll() {
    return 'This action returns all users';
  }
}

Now, every GET request to /users will include the Cache-Control: none header in the response.

Interesting Fact: While you can directly interact with the underlying Express response object for more complex scenarios, for most common use cases, these decorators keep your code clean and declarative, which is the NestJS way!


📚 Extra Reading and References

Challenge

Challenge: Implement a Product Update Endpoint

Your task is to implement a full-featured PATCH endpoint within a NestJS ProductsController to handle partial updates for a product. You will need to create a Data Transfer Object (DTO) with validation and a controller method that uses decorators to manage the request and response.

Requirements:

  1. Create an UpdateProductDto class:

    • It must define three properties: name (string), price (number), and inStock (boolean).
    • All three properties must be optional, as a PATCH request might only update a subset of fields.
    • Apply validation decorators from class-validator:
      • name must be a non-empty string if provided.
      • price must be a positive number if provided.
      • inStock must be a boolean if provided.
  2. Implement the updateProduct method inside ProductsController:

    • The method must handle PATCH requests to the path /:id.
    • It must extract the id from the URL route parameters.
    • It must accept the request body and validate it against the UpdateProductDto.
    • Upon successful validation, the endpoint should be configured to return an HTTP status code of 204 No Content.
    • The response must include a custom header X-Last-Updated with a static string value of '2023-10-27T10:00:00Z'.

Expected result

Your code should define a validated DTO and a controller method that correctly uses NestJS decorators for routing, parameter binding, and response customization.

typescript
import { Controller, Param, Body, Patch, HttpCode, Header } from '@nestjs/common';
import { IsString, IsPositive, IsBoolean, IsOptional, IsNotEmpty } from 'class-validator';

export class UpdateProductDto {
  @IsOptional()
  @IsString()
  @IsNotEmpty()
  name?: string;

  @IsOptional()
  @IsPositive()
  price?: number;

  @IsOptional()
  @IsBoolean()
  inStock?: boolean;
}

@Controller('products')
export class ProductsController {
    @Patch(':id')
    @HttpCode(204)
    @Header('X-Last-Updated', '2023-10-27T10:00:00Z')
    updateProduct(@Param('id') id: string, @Body() updateProductDto: UpdateProductDto) {
        // In a real application, logic to update the product with 'id'
        // using 'updateProductDto' would go here.
        return;
    }
}

Explanation:

  • The UpdateProductDto class correctly uses @IsOptional() on all properties, making them suitable for a PATCH operation. It also includes specific type validation (@IsString, @IsPositive, @IsBoolean) and content validation (@IsNotEmpty).
  • The updateProduct method is decorated with @Patch(':id') to bind it to the correct HTTP method and route pattern.
  • @Param('id') correctly extracts the dynamic id segment from the URL.
  • @Body() extracts the request payload and, when used with a DTO and a ValidationPipe (assumed to be globally enabled), triggers automatic validation.
  • @HttpCode(204) overrides the default 200 OK status for a successful response.
  • @Header(...) adds the specified custom header to the response.
typescript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.