← Back
nestjs

Nested controllers in Nestjs

It's common to have nested routes in REST APIs. Basically, I mean having routes like this:

/post/:id <- PARENT ROUTE
/post/:id/comments <- NESTED ROUTE
/post/:id/comments/:id <- NESTED ROUTE

And two controllers: the Post controller (first route) and the PostComments controller (nested routes)

By looking at the nestjs documentation is not easy to know how to do it.

But here's an example:

@Controller("posts/:postId")
export class PostCommentsController {

@Get("comments")
async listComments(@Param() params): Promise<CommentResponse[]> {
const { postId } = params;
...
}
@Get("comments/:commentId")
async getComment(@Param() params): Promise<CommentResponse> {
const { postId, commentId } = params;
}
}

We need to specify the parent route in the @Controller annotation.

In fact, PostCommentsController is not strictly nested (when you change the parent controller url, the child controller urls are not updated). But it works!

🖖