How to Create Routes in NestJS: Simple Guide
In NestJS, you create a route by defining a controller class and using the
@Controller decorator with route path, then add methods with HTTP method decorators like @Get to handle requests. Each method corresponds to a route endpoint that NestJS listens to.Syntax
To create a route in NestJS, use the @Controller('path') decorator on a class to set the base route path. Inside the class, use HTTP method decorators like @Get(), @Post(), @Put(), or @Delete() on methods to define specific endpoints.
The method name can be anything, but the decorator defines the route and HTTP method.
typescript
import { Controller, Get } from '@nestjs/common'; @Controller('example') export class ExampleController { @Get('route') getExample() { return 'Hello from route!'; } }
Example
This example shows a simple NestJS controller with a route /hello that responds to GET requests with a greeting message.
typescript
import { Controller, Get } from '@nestjs/common'; @Controller('hello') export class HelloController { @Get() sayHello() { return 'Hello, NestJS!'; } }
Output
When you visit http://localhost:3000/hello in your browser, you will see the text: Hello, NestJS!
Common Pitfalls
- Forgetting to add the controller to the module's
controllersarray will make the route unreachable. - Not specifying a path in
@Controller()or HTTP method decorators defaults to root or empty path, which can cause route conflicts. - Using the wrong HTTP method decorator (e.g.,
@Postinstead of@Get) will cause unexpected behavior.
typescript
/* Wrong: Controller not added to module */ import { Controller, Get } from '@nestjs/common'; @Controller('test') export class TestController { @Get() test() { return 'Test'; } } /* Right: Add controller to module */ import { Module } from '@nestjs/common'; @Module({ controllers: [TestController], }) export class AppModule {}
Quick Reference
| Decorator | Purpose | Example |
|---|---|---|
| @Controller('path') | Defines base route path for the controller | @Controller('users') |
| @Get('subpath') | Handles GET requests at 'basepath/subpath' | @Get('profile') |
| @Post('subpath') | Handles POST requests at 'basepath/subpath' | @Post('create') |
| @Put('subpath') | Handles PUT requests at 'basepath/subpath' | @Put('update') |
| @Delete('subpath') | Handles DELETE requests at 'basepath/subpath' | @Delete('remove') |
Key Takeaways
Use @Controller to set the base route path for a group of routes.
Use HTTP method decorators like @Get, @Post on methods to define specific routes.
Always add your controllers to the module's controllers array to activate routes.
Route paths in decorators combine to form the full URL endpoint.
Choose the correct HTTP method decorator to match the intended request type.