0
0
NestjsHow-ToBeginner ยท 3 min read

How to Use @Param Decorator in NestJS for Route Parameters

In NestJS, use the @Param decorator inside a controller method to access route parameters from the URL. You can get all parameters as an object or a specific parameter by passing its name to @Param('paramName').
๐Ÿ“

Syntax

The @Param decorator extracts parameters from the route URL in a controller method. You can use it in two ways:

  • @Param() without arguments to get all parameters as an object.
  • @Param('paramName') with a string argument to get a specific parameter value.

It is used as a parameter decorator in controller methods that handle HTTP requests.

typescript
@Get(':id')
getById(@Param('id') id: string) {
  return `ID is ${id}`;
}

@Get()
getAllParams(@Param() params: Record<string, string>) {
  return params;
}
๐Ÿ’ป

Example

This example shows a simple NestJS controller using @Param to get a user ID from the URL and return it in the response.

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

@Controller('users')
export class UsersController {
  @Get(':id')
  getUserById(@Param('id') id: string) {
    return { message: `User ID requested is ${id}` };
  }

  @Get(':userId/books/:bookId')
  getUserBook(
    @Param('userId') userId: string,
    @Param('bookId') bookId: string
  ) {
    return { message: `User ${userId} requested book ${bookId}` };
  }
}
Output
GET /users/42 => { "message": "User ID requested is 42" } GET /users/42/books/7 => { "message": "User 42 requested book 7" }
โš ๏ธ

Common Pitfalls

Common mistakes when using @Param include:

  • Forgetting to specify the parameter name inside @Param('name') when you want a single value.
  • Using the wrong parameter name that does not match the route definition.
  • Not converting parameter types (all params are strings by default).

Always ensure the route path and @Param names match exactly.

typescript
/* Wrong: parameter name does not match route */
@Get(':userId')
getUser(@Param('id') id: string) {
  return id; // undefined because route param is 'userId'
}

/* Right: matching parameter name */
@Get(':userId')
getUser(@Param('userId') userId: string) {
  return userId; // correct value
}
๐Ÿ“Š

Quick Reference

UsageDescriptionExample
@Param()Get all route parameters as an object@Param() params => { id: '42', name: 'john' }
@Param('id')Get specific route parameter by name@Param('id') id => '42'
Type conversionParams are strings; convert if neededconst idNum = Number(id)
โœ…

Key Takeaways

Use @Param('name') to get a specific route parameter by its name.
Use @Param() to get all route parameters as an object.
Ensure the parameter name in @Param matches the route path exactly.
Route parameters are strings by default; convert types as needed.
@Param works only inside controller methods handling routes.