Query parameters let you send extra information in a URL to tell the server what data you want. They help make your app flexible and interactive.
Query parameters in NestJS
import { Controller, Get, Query } from '@nestjs/common'; @Controller('items') export class ItemsController { @Get() getItems(@Query('color') color: string) { return `Items filtered by color: ${color}`; } }
The @Query() decorator extracts query parameters from the URL.
You can get a single parameter by name or all parameters as an object.
getItems(@Query('color') color: string) { return `Color is ${color}`; }
getItems(@Query() query: Record<string, string>) {
return query;
}getItems(@Query('page') page: string = '1') { return `Page number is ${page}`; }
This controller handles GET requests to '/products'. It reads optional query parameters 'category' and 'sort'. If they are missing, it uses default values. The response shows what filters and sorting are applied.
import { Controller, Get, Query } from '@nestjs/common'; @Controller('products') export class ProductsController { @Get() getProducts( @Query('category') category?: string, @Query('sort') sort?: string ) { return { message: 'Products fetched', filter: category || 'all', sortOrder: sort || 'default' }; } }
Query parameters are always strings in URLs, so convert them if you need numbers.
Use optional parameters with '?' to avoid errors if the query is missing.
Query parameters help keep URLs clean and flexible without changing routes.
Query parameters let you send extra info in URLs to control data returned.
Use @Query() in NestJS to access these parameters easily.
They are great for filtering, sorting, and pagination in your apps.