0
0
NestJSframework~5 mins

Query parameters in NestJS

Choose your learning style9 modes available
Introduction

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.

When you want to filter a list of items, like showing only red shirts in a store.
When you want to sort data, like ordering products by price or name.
When you want to paginate results, like showing page 2 of search results.
When you want to pass optional settings without changing the URL path.
When you want to search or find specific data based on user input.
Syntax
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.

Examples
Gets a single query parameter named 'color'.
NestJS
getItems(@Query('color') color: string) {
  return `Color is ${color}`;
}
Gets all query parameters as an object.
NestJS
getItems(@Query() query: Record<string, string>) {
  return query;
}
Gets 'page' parameter with a default value if not provided.
NestJS
getItems(@Query('page') page: string = '1') {
  return `Page number is ${page}`;
}
Sample Program

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.

NestJS
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'
    };
  }
}
OutputSuccess
Important Notes

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.

Summary

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.