Open In App

How To Use Query Parameters in NestJS?

Last Updated : 26 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Step 6: Install Class Validator and Class Transformer

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

NestJs_Query_params_folder_Strucutre
Folder Structure

Approach 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

Nestjs_Approach_1_output
Using @Query() Decorator

Approach 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:

NestJs_Approach_2_output
Setting Default Query Parameters

Approach 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.

NestJs_Approach_3_output
Validating Query Parameters

Approach 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:

Nestjs_Approach_4_output
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:

Nestjs_Approach_5_Output_1
Optional Query Parameters

If you visit http://localhost:3000/users?name=John, the response will be:

Nestjs_Approach_5_output_2
Optional Query Parameters

Next Article

Similar Reads