Adding route prefixes to specific modules in NestJS is a straightforward process. This is typically achieved by setting the controllers property within the @Module decorator of the module. To add prefixes to all controllers under a specific module, use the @Controller decorator at the module level and specify the prefix within it. Below are the steps to follow:
- Import the
ModuleandControllerdecorators:
typescriptimport { Module, Controller } from '@nestjs/common';
- Use the
@Controllerdecorator in the module's controller and specify the route prefix:
typescript@Controller('prefix') export class YourController { // ... }
In the above code, 'prefix' is the route prefix set for this controller. This means that if your controller has a route decorator like @Get('example'), the final route will be /prefix/example.
- Of course, you can also set a prefix at the module level to automatically apply it to all controllers registered within the module. First, ensure your module is defined using the
@Moduledecorator, like this:
typescript@Module({ controllers: [YourController], // ... (other properties like providers, exports, etc.) }) export class YourModule {}
- Next, to add route prefixes to all controllers within the entire module, utilize the module class's constructor and the
setGlobalPrefixmethod. For example, you can do this in the main.ts file:
typescriptimport { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule); app.setGlobalPrefix('api'); await app.listen(3000); } bootstrap();
The above code sets a global prefix api for all routes in the application. However, if you only want to set a prefix for a specific module rather than globally, do not use the setGlobalPrefix method.
- For setting prefixes on specific modules, create a base controller class that uses the
@Controllerdecorator to add the prefix, and have all controllers within the module inherit this base controller.
Example:
typescript@Controller('modulePrefix') export class BaseModuleController {} export class ActualController extends BaseModuleController { @Get('example') exampleMethod() { // ... } }
In this example, ActualController inherits from BaseModuleController, meaning all routes defined in ActualController automatically include the modulePrefix prefix. Therefore, the final route for the exampleMethod method is /modulePrefix/example.
By following these steps, you can effectively add route prefixes to specific modules in your NestJS application to organize and manage your API endpoints.