CodePark/ questions / Middleware & request lifecycle
START PRACTICINGPRACTICE
Backend question · NestJS › Middleware & request lifecycle

You need to check a @Roles() decorator on the target handler before it runs. Why can't middleware do this reliably?

Middleware has no ExecutionContext, so it doesn't know which handler or class will run

Middleware is called with only req, res and next. Nest hasn't built an execution context for the handler yet, so middleware can't read handler metadata like @Roles(). Guards get an ExecutionContext with getHandler() and getClass(). That's why role checks belong in a guard.

The other options are false. "Middleware can't read request headers" is wrong: it can. "Middleware can't throw exceptions" is wrong: it can. "Middleware runs after guards" is wrong: it runs before guards.