Routing & Path Prefixes

The controller prefix and the method decorator combine to form a route path.

Syntax@Get('sub-path')

Nest builds a route from two parts: the prefix on the controller and the path on the method decorator.

Combining paths

A controller with prefix users and a method decorated @Get('profile') answers requests to /users/profile. An empty @Get() maps to the prefix itself, /users.

This grouping keeps related endpoints together and avoids repeating the base path on every method.

Example

Example · typescript
import { Controller, Get } from '@nestjs/common';

@Controller('users')
export class UsersController {
  @Get()          // GET /users
  findAll() {
    return 'all users';
  }

  @Get('active')  // GET /users/active
  findActive() {
    return 'active users';
  }
}

When to use it

  • A developer sets @Controller("products") so all product routes share the /products prefix without repeating it in every method decorator.
  • A team nests a sub-resource under the controller prefix (e.g., @Get(":id/reviews")) to express parent-child relationships in the URL.
  • An API uses @Controller("v2/users") to version an entire controller's routes while keeping the old controller untouched.

More examples

Controller prefix and method path

Shows how the controller prefix and method decorator path combine to build the full route.

Example · ts
import { Controller, Get } from '@nestjs/common';

@Controller('products')   // prefix: /products
export class ProductsController {
  @Get()              // GET /products
  findAll() {}

  @Get('featured')   // GET /products/featured
  findFeatured() {}
}

Nested sub-resource route

Demonstrates defining a sub-resource route by combining a dynamic prefix segment with a static sub-path.

Example · ts
import { Controller, Get, Param } from '@nestjs/common';

@Controller('products')
export class ProductsController {
  @Get(':id/reviews')   // GET /products/42/reviews
  getReviews(@Param('id') id: string) {
    return `Reviews for product ${id}`;
  }
}

Versioned controller prefix

Illustrates URL-based versioning by embedding the version in the controller prefix so V1 routes remain unaffected.

Example · ts
import { Controller, Get } from '@nestjs/common';

@Controller('v2/users')   // all routes: /v2/users/...
export class UsersV2Controller {
  @Get()   // GET /v2/users
  findAll() { return []; }

  @Get(':id')   // GET /v2/users/1
  findOne(@Param('id') id: string) {}
}

Discussion

  • Be the first to comment on this lesson.