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
How to Get Query Parameters from URL in Next.js?
In Next.js, getting query parameters from the URL involves extracting key-value pairs from the URL string to access specific data or parameters associated with a web page or application, aiding in dynamic content generation and customization.To get query parameters from the URL in next.js we have mu
5 min read
How to Create Query Parameters in JavaScript ?
Creating query parameters in JavaScript involves appending key-value pairs to a URL after the `?` character. This process is essential for passing data to web servers via URLs, enabling dynamic and interactive web applications through GET requests and URL manipulation. Example: Input: {'website':'ge
3 min read
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 af
2 min read
How To Perform Unit Test in NestJS?
NestJS is a Node.js framework for building efficient, reliable and scalable server-side applications. It is built using TypeScript and It offers support for unit testing through the Jest testing framework. In this article, we will learn about performing unit testing in a NestJs.Table of ContentWhat
5 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 Parameters from a URL in VueJS ?
Query parameters are part of a URL that assigns values to specified parameters. They start after the question mark and are separated by ampersands ("&") in the URL. For example, in the URL https://example.com?name=John&age=23, name=John and age=23 are query parameters. The below-listed metho
8 min read
How to Get Query String Parameter in SvelteKit?
In this article, we will explore how to retrieve query string parameters in SvelteKit applications. Query parameters are often used to pass data in URLs, such as user preferences or search queries. Understanding how to access these parameters is crucial for building dynamic web applications.These ar
3 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