CodePark/ questions / Controllers & routing
START PRACTICINGPRACTICE
Backend question · NestJS › Controllers & routing

A controller declares @Get(":id") before @Get("me"). Requests to /users/me hit the wrong handler. Why, and how do you fix it?

The :id route is declared first, and it matches me too. With the Express platform, Nest registers routes in the order the handlers appear in the class. The :id pattern matches any single path segment, including the word me. So the :id handler matches /users/me first, and findOne("me") runs.

Fixes:

  • Declare static routes before routes with params. Put @Get("me") above @Get(":id").
  • Make the param stricter by validating it, for example with ParseUUIDPipe or ParseIntPipe. Then a bad value fails with a 400 error, instead of silently reaching the wrong logic.

The general rule for any wildcard or param route: put the more specific routes first.

  • Routes are matched in the order they are declared.
  • :id matches any segment, including me.
  • Declare static routes before routes with params.
  • Validate params with ParseUUIDPipe or ParseIntPipe.