0
0
NestJSframework~5 mins

Route parameters in NestJS

Choose your learning style9 modes available
Introduction

Route parameters let you capture parts of a URL to use in your code. This helps you handle dynamic data like user IDs or product names.

When you want to get a user ID from the URL to show that user's profile.
When you need to fetch a specific product based on its ID in the URL.
When you want to handle different pages or items using one route pattern.
When building REST APIs that require resource identifiers in the URL.
Syntax
NestJS
@Get(':parameterName')
methodName(@Param('parameterName') param: string) {
  // use param here
}

The colon : before the parameter name in the route path marks it as a variable.

The @Param() decorator extracts the parameter value from the URL.

Examples
This example captures the id from the URL and returns it as a string.
NestJS
@Get(':id')
getUser(@Param('id') id: string) {
  return `User ID is ${id}`;
}
Here, the route expects a URL like /product/123 and extracts 123 as productId.
NestJS
@Get('product/:productId')
getProduct(@Param('productId') productId: string) {
  return `Product ID: ${productId}`;
}
This example shows multiple route parameters in one URL, like /books/456.
NestJS
@Get(':category/:itemId')
getItem(
  @Param('category') category: string,
  @Param('itemId') itemId: string
) {
  return `Category: ${category}, Item ID: ${itemId}`;
}
Sample Program

This controller listens to URLs like /users/42. It extracts 42 as userId and returns a message with it.

NestJS
import { Controller, Get, Param } from '@nestjs/common';

@Controller('users')
export class UsersController {
  @Get(':userId')
  getUserById(@Param('userId') userId: string): string {
    return `User ID received: ${userId}`;
  }
}
OutputSuccess
Important Notes

Route parameters are always strings. Convert them if you need numbers.

You can use multiple parameters in one route to capture more data.

Be careful with parameter names; they must match between the route and the @Param() decorator.

Summary

Route parameters let you get dynamic parts of the URL.

Use : in the route path and @Param() to access them.

This helps build flexible and reusable routes in NestJS.