In NestJS, routes are defined within controllers and mapped to HTTP methods like GET
, POST
, PUT
, and DELETE
. Here’s an overview of how to create and manage routes in NestJS:
Table of Contents
1. Basic Route Structure
Routes in NestJS are defined in controllers using decorators like @Get
, @Post
, @Put
, @Delete
, etc.
Example:
typescriptCopy codeimport { Controller, Get, Post, Param, Body } from '@nestjs/common';
@Controller('users') // Base path for all routes in this controller
export class UsersController {
// GET /users
@Get()
findAll(): string {
return 'This will return all users.';
}
// GET /users/:id
@Get(':id')
findOne(@Param('id') id: string): string {
return `This will return the user with ID ${id}`;
}
// POST /users
@Post()
create(@Body() createUserDto: any): string {
return 'This will create a new user.';
}
}
2. Route Parameters
You can define dynamic route parameters using the @Param()
decorator.
Example:
typescriptCopy code@Get(':id')
findOne(@Param('id') id: string): string {
return `User with ID: ${id}`;
}
3. Query Parameters
Use the @Query()
decorator to handle query strings.
Example:
typescriptCopy code@Get()
findWithQuery(@Query('role') role: string): string {
return `This will return users with role: ${role}`;
}
Request example: GET /users?role=admin
4. Request Body
The @Body()
decorator is used to handle incoming request bodies, often in POST
or PUT
routes.
Example:
typescriptCopy code@Post()
create(@Body() createUserDto: any): string {
return `User created with data: ${JSON.stringify(createUserDto)}`;
}
5. Route Guards and Middleware
To add authentication or authorization logic, you can use:
- Guards: Protect specific routes.
- Middleware: Apply logic before requests reach controllers.
Example: Adding a guard
typescriptCopy codeimport { Controller, Get, UseGuards } from '@nestjs/common';
import { AuthGuard } from './auth.guard';
@Controller('secure')
export class SecureController {
@Get()
@UseGuards(AuthGuard)
findSecureData(): string {
return 'This is protected data.';
}
}
6. Grouping Routes with Modules
Controllers are registered in modules. For example, in app.module.ts
:
typescriptCopy codeimport { Module } from '@nestjs/common';
import { UsersController } from './users/users.controller';
@Module({
imports: [],
controllers: [UsersController],
providers: [],
})
export class AppModule {}
7. Prefixing Routes
You can define global route prefixes in main.ts
:
Example:
typescriptCopy codeconst app = await NestFactory.create(AppModule);
app.setGlobalPrefix('api');
await app.listen(3000);
Routes will now be prefixed with /api
:
GET /api/users
POST /api/users
8. Handling Sub-Routes
NestJS supports nested controllers for handling sub-routes.
Example:
typescriptCopy code@Controller('users')
export class UsersController {
@Get('profile')
getProfile(): string {
return 'User profile route';
}
@Get('settings')
getSettings(): string {
return 'User settings route';
}
}
Routes:
GET /users/profile
GET /users/settings
9. Custom Route Decorators – Routes in NestJS
You can create custom route decorators for cleaner and reusable code.
Example:
typescriptCopy codeimport { createParamDecorator, ExecutionContext } from '@nestjs/common';
export const User = createParamDecorator(
(data: unknown, ctx: ExecutionContext) => {
const request = ctx.switchToHttp().getRequest();
return request.user;
},
);
@Get('me')
getProfile(@User() user: any) {
return user;
}
With these examples, you can efficiently create and manage routes in NestJS for a scalable and organized application!
How to create routes in nest js
In NestJS, routes are created using controllers. Controllers handle incoming requests and define endpoints for your application. Below is a step-by-step guide to creating routes in NestJS:
1. Install NestJS (if not done already)
Ensure you have NestJS installed. You can create a new project using the Nest CLI:
npm i -g @nestjs/cli
nest new my-nest-app
cd my-nest-app
2. Generate a Controller
Use the Nest CLI to generate a controller:
nest generate controller <controller-name>
For example:
nest generate controller users
This creates a users.controller.ts
file with a basic structure.
3. Define Routes in the Controller
Open the generated controller file (users.controller.ts
) and define the routes using decorators like @Get
, @Post
, @Put
, @Delete
, etc.
Example:
import { Controller, Get, Post, Param, Body } from '@nestjs/common';
@Controller('users') // Base route
export class UsersController {
// GET /users
@Get()
findAll(): string {
return 'This action returns all users';
}
// GET /users/:id
@Get(':id')
findOne(@Param('id') id: string): string {
return `This action returns user with ID: ${id}`;
}
// POST /users
@Post()
create(@Body() createUserDto: any): string {
return 'This action creates a new user';
}
}
4. Use a Module to Register the Controller
Controllers are registered in a module. By default, NestJS generates a AppModule
or the module associated with the controller.
In the app.module.ts
file:
import { Module } from '@nestjs/common';
import { UsersController } from './users/users.controller';
@Module({
imports: [],
controllers: [UsersController],
providers: [],
})
export class AppModule {}
5. Start the Application
Run the application to test the routes:
npm run start
6. Test the Routes
You can test the routes using tools like:
- Postman
- cURL
- Browser (for simple GET requests)
For example:
- Navigate to
http://localhost:3000/users
(GET all users). - Navigate to
http://localhost:3000/users/1
(GET user with ID1
).
7. Advanced Features
You can add more advanced features to your routes:
- Middleware: Add logic before requests reach the controller.
- Guards: Handle authentication and authorization.
- Interceptors: Transform or log responses.
- Validation Pipes: Validate request data.
This is the basic approach to creating and working with routes in NestJS!