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.
Practice
@Query() decorator in a NestJS controller?Solution
Step 1: Understand the role of
The@Query()@Query()decorator extracts query parameters from the URL in a GET request.Step 2: Compare with other decorators
Other decorators like@Body()handle POST bodies, and@Param()handles route params, so they don't fit here.Final Answer:
To access query parameters sent in the URL -> Option DQuick Check:
@Query()reads URL queries = A [OK]
@Query() reads URL query strings [OK]- Confusing
@Query()with@Body() - Thinking
@Query()defines routes - Using
@Query()to inject services
page in a NestJS controller method?Solution
Step 1: Identify correct decorator usage
To get a specific query parameter, use@Query('paramName')syntax.Step 2: Check syntax correctness
async getItems(@Query('page') page: number) {} uses@Query('page')correctly. Options A and C use wrong decorators, and D has invalid syntax.Final Answer:
async getItems(@Query('page') page: number) {} -> Option CQuick Check:
Use@Query('param')for query params = B [OK]
@Query('name') to get specific query param [OK]- Using
@Param()instead of@Query() - Trying to access query param as
@Query.page - Using
@Body()for query parameters
async find(@Query() query) {
return query.page + '-' + query.limit;
}What will be the output if the URL is
/items?page=2&limit=5?Solution
Step 1: Understand
The@Query()behavior@Query()decorator without arguments returns an object with all query parameters as strings.Step 2: Check the returned string concatenation
With URL?page=2&limit=5,query.pageis "2" andquery.limitis "5". Concatenation returns "2-5".Final Answer:
"2-5" -> Option AQuick Check:
Query object has keys = "2-5" [OK]
@Query() gets all query params as object [OK]- Expecting numbers instead of strings from query params
- Assuming
@Query()returns undefined - Thinking it causes runtime error
search?:async search(@Query(search) searchTerm: string) {
return searchTerm;
}Solution
Step 1: Check
The argument to@Querydecorator syntax@Query()must be a string literal naming the query parameter, e.g.,@Query('search').Step 2: Identify the error in the code
The code uses@Query(search)without quotes, which is invalid syntax and causes an error.Final Answer:
The@Querydecorator argument should be a string:@Query('search')-> Option BQuick Check:
Decorator argument must be string literal = D [OK]
@Query('name') [OK]- Forgetting quotes around query param name
- Using
@Param()for query params - Thinking async keyword is disallowed
sort and filter. If filter is missing, it should default to "all". Which code snippet correctly implements this behavior?Solution
Step 1: Understand default value handling for query params
Query parameters come as strings or undefined. Default values should be set inside the method, not in parameter defaults.Step 2: Analyze each option
async getItems(@Query('sort') sort: string, @Query('filter') filter: string = 'all') {} tries to set default in parameter, which doesn't work well with@Query(). async getItems(@Query() query) { const filter = query.filter || 'all'; return { sort: query.sort, filter }; } extracts all query params and sets default forfilterinside method correctly. async getItems(@Query('sort') sort: string, @Query('filter') filter?: string) { if (!filter) filter = 'all'; return { sort, filter }; } tries to assign to parameter which is readonly. async getItems(@Query('sort') sort: string, @Query('filter') filter: string) { filter = filter ?? 'all'; return { sort, filter }; } assigns default after parameter, but parameter is readonly, so it causes error.Final Answer:
async getItems(@Query() query) { const filter = query.filter || 'all'; return { sort: query.sort, filter }; } -> Option AQuick Check:
Set defaults inside method body = A [OK]
- Trying to assign default values in parameter list with
@Query() - Mutating readonly parameters
- Not handling missing query params properly
Ready to prove it?
Pass the test and this pattern moves unknown
