How To Use Query Parameters in NestJS?
Last Updated :
26 Sep, 2024
NestJS is a popular framework for building scalable server-side applications using Node.js. It is built on top of TypeScript and offers a powerful yet simple way to create and manage APIs. One of the core features of any web framework is handling query parameters, which allow developers to pass data through URLs. This article will focus on how to use query parameters in NestJS, their different use cases, and best practices for working with them.
What Are Query Parameters?
Query parameters are key-value pairs appended to the end of a URL after a question mark (?). They are used to send additional data in HTTP requests and are often used to filter, paginate, or sort resources.
For example:
https://example.com/api/users?page=2&limit=10
In this URL, page=2 and limit=10 are query parameters. The page parameter might be used for pagination, and limit to specify the number of items per page.
Primary Terminology
- Query Parameters: Key-value pairs added to the URL after a ?, used for filtering or modifying requests (e.g., http://localhost:3000/users?name=John).
- Decorators: Special functions in NestJS that can modify methods, properties, or parameters.
- DTO (Data Transfer Object): A class that ensures validation and type checking when transferring data.
- Pipes: A NestJS mechanism for transforming or validating incoming data.
- ValidationPipe: A built-in feature that validates requests using rules defined in DTOs.
How to Access Query Parameters in NestJS?
NestJS makes it simple to access query parameters using decorators. The most common approach to accessing query parameters is by using the @Query decorator provided by NestJS. It automatically parses the query parameters into an object and makes it accessible inside your route handler functions. You can retrieve individual query parameters or the entire query object.
Various Approach To Use Query Parameters in NestJS
Steps To Use Query Parameters in NestJS
To create a project in NestJS and handle query parameters, follow these steps:
Step 1: Install Node.js
Ensure you have Node.js installed on your system. You can download it from Node.js official website.
Step 2: Install the Nest CLI
To create and manage a NestJS project, install the Nest CLI globally on your system:
npm install -g @nestjs/cli
Step 3: Create a New NestJS Project
Use the Nest CLI to create a new NestJS project
nest new my-nestjs-query-params
This will prompt you to choose a package manager (choose between npm or yarn). Once selected, the CLI will install the dependencies for you.
Step 4: Navigate to the Project Directory
Move into the newly created project directory:
cd my-nestjs-query-params
Step 5: Generate a Controller
Generate a new controller where you will handle query parameters:
nest generate controller user
This will create a user.controller.ts file inside the src/user/ directory.
First, ensure the necessary packages are installed:
npm install class-validator class-transformer
Updated Dependencies
"dependencies": {
"@nestjs/common": "^10.0.0",
"@nestjs/core": "^10.0.0",
"@nestjs/platform-express": "^10.0.0",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.1",
"reflect-metadata": "^0.2.0",
"rxjs": "^7.8.1"
}
Folder Structure
Folder StructureApproach 1: Using @Query() Decorator
The most basic and widely used approach to handle query parameters is the @Query() decorator in NestJS. It extracts the query parameters from the request and makes them available in the controller handler.
Syntax:
@Query(parameter: string): any
Example: In the example Below, the @Query('name') extracts the name parameter from the URL like /users?name=John.
JavaScript
// src/users/user.controller.ts
import { Controller, Get, Query } from '@nestjs/common';
@Controller('users')
export class UserController {
@Get()
getUser(@Query('name') name: string) {
return `User name is: ${name}`;
}
}
Start The Project for using below command
npm run start
If you visit http://localhost:3000/users?name=John You will get desired output
Output
Using @Query() DecoratorApproach 2: Setting Default Query Parameters
Sometimes, query parameters might not always be provided by the user. You can set default values for query parameters in such cases.
Syntax:
getUser(@Query('name', { defaultValue: 'Guest' }) name: string)
Example:
Explanation:
- The name parameter is given a default value of 'Guest'.
- If no query parameter is provided, the system will default to using 'Guest'.
JavaScript
// src/users/user.controller.ts
import { Controller, Get, Query } from '@nestjs/common';
@Controller('users')
export class UserController {
@Get()
getUser(@Query('name') name: string = 'Guest') {
return `User name is: ${name}`;
}
}
Output
If the URL is http://localhost:3000/users, the response will be:
Setting Default Query ParametersApproach 3: Validating Query Parameters
Using validation helps ensure that the query parameters meet certain criteria (e.g., non-empty strings). For this, we'll use DTOs (Data Transfer Objects) and the class-validator package.
Syntax
@Query(parameter: string): Type
Example: Create a new query.dto.ts file in the src/user/ directory.
- A DTO (QueryDto) is used to validate the name parameter.
- The @IsString() and @IsNotEmpty() decorators ensure the name is a non-empty string.
JavaScript
// src/users/query.dto.ts
import { IsString, IsNotEmpty } from 'class-validator';
export class QueryDto {
@IsString()
@IsNotEmpty()
name: string;
}
JavaScript
// src/users/user.controller.ts
import { Controller, Get, Query } from '@nestjs/common';
import { QueryDto } from './query.dto';
@Controller('users')
export class UserController {
@Get()
getUser(@Query() query: QueryDto) {
return `User name is: ${query.name}`;
}
}
Output
Visiting http://localhost:3000/users?name= will throw a validation error because the name cannot be empty.
Validating Query ParametersApproach 4: Handling Multiple Query Parameters
Sometimes, you might need to extract multiple query parameters in one controller method. NestJS allows you to do this by passing multiple parameters into the @Query() decorator.
Syntax
@Query(): object
Example
- We extract two query parameters, name and age, from the URL.
- Both values are returned in the response.
JavaScript
//src/users/user.controller.ts
import { Controller, Get, Query } from '@nestjs/common';
@Controller('users')
export class UserController {
@Get()
getUser(
@Query('name') name: string,
@Query('age') age: number
) {
return `User name is ${name} and age is ${age}`;
}
}
Output
Visiting http://localhost:3000/users?name=John&age=25 will return:
Handling Multiple Query Parameters
Approach 5: Optional Query Parameters
In this approach, the query parameter is optional and the method will respond differently based on whether the parameter is provided.
Syntax
@Query(): parameterName?
Example
- The name parameter is optional (name?: string).
- If no query parameter is provided, the response will default to "No name provided".
JavaScript
// src/users/user.controller.ts
import { Controller, Get, Query } from '@nestjs/common';
@Controller('users')
export class UserController {
@Get()
getUser(@Query('name') name?: string) {
return name ? `User name is: ${name}` : 'No name provided';
}
}
Output
If the URL is http://localhost:3000/users, the response will be:
Optional Query ParametersIf you visit http://localhost:3000/users?name=John, the response will be:
Optional Query Parameters
Similar Reads
Reading Query Parameters in Node
In Node.js, query parameters are typically accessed from the URL of a GET request. When using the core HTTP module or a framework like Express, query parameters can be parsed and accessed for dynamic functionality. A query string refers to the portion of a URL (Uniform Resource Locator) that comes a
2 min read
How to use get parameter in Express.js ?
Express Js is a web application framework on top of Node.js web server functionality that reduces the complexity of creating a web server. Express provides routing services i.e., how an application endpoint responds based on the requested route and the HTTP request method (GET, POST, PUT, DELETE, UP
2 min read
How to Get query params using Server component in Next.js ?
NextJS is a React framework that is used to build full-stack web applications. It is used both for front-end as well as back-end. It comes with a powerful set of features to simplify the development of React applications. We will discuss different approaches to get query params using the server comp
3 min read
How to receive post parameter in Express.js ?
Express is a small framework that sits on top of Node.jsâs web server functionality to simplify its APIs and add helpful new features. It makes it easier to organize your applicationâs functionality with middleware and routing; it adds helpful utilities to Node.jsâs HTTP objects; it facilitates the
3 min read
How to Get Parameter Value from Query String in ReactJS?
In React query parameter are a way to pass the data as props from the url to react components. Getting parameter value from query string helps to render the dynamic data depending on the query. ApproachTo get the parameter value from query string in React we will be using the query-string packge. We
2 min read
How do you access query parameters in an Express JS route handler?
Express JS is a popular web framework for Node JS, simplifies the development of web applications. One common task is accessing query parameters from URLs within route handlers. In this article, we'll explore the fundamentals of working with query parameters in Express JS and demonstrate how to acce
2 min read
How to get URL Parameters using JavaScript ?
To get URL parameters using JavaScript means extracting the query string values from a URL. URL parameters, found after the ? in a URL, pass data like search terms or user information. JavaScript can parse these parameters, allowing you to programmatically access or manipulate their values. For gett
3 min read
How to pass query parameters with a routerLink ?
The task is to pass query parameters with a routerLink, for that we can use the property binding concept to reach the goal. Using property binding, we can bind queryParams property and can provide the required details in the object. What is Property Binding? It is a concept where we use square brack
2 min read
Explain the Rest parameter in ES6
In this article, we will try to understand the details associated with the rest parameter in ES6 which includes the syntax of rest parameters, and how to use this with the help of certain examples. The rest parameter is an improved way to handle function parameters, allowing us to handle various inp
3 min read
How does Query.prototype.intersects() work in Mongoose ?
The Query.prototype.intersects() function is used to declare an intersects query for geometry(). This function is widely used with geometry function. Syntax: Query.prototype.intersects() Parameters: This function has one arg parameter of the Object type.Return Value: This function returns Query Obje
2 min read