Skip to content

Guards run before body parsing, so request.body is a pending Promise inside canActivate #206

Description

@nicoske

On Express, body-parser runs before the Nest pipeline, so a guard can read request.body.userId and get a value. On UwsPlatformAdapter (2.0.1 and main) the route registry executes guards first and only awaits req.body afterwards, so inside canActivate the getter returns an unresolved Promise. Every auth guard that authorizes against payload fields breaks silently: the reads come back undefined and valid requests get rejected.

The same root cause bites libraries that read request.body synchronously. Nestia's @TypedBody is the one I ran into: it validates whatever request.body returns without awaiting, so it ends up validating a Promise and rejects every request with all fields undefined.

There is a second wrinkle: the awaited body is only stored back on the request when pipes are configured (_setTransformedBody is called in the pipes branch only). For routes without pipes, even the handler gets a fresh Promise from the getter although the registry has already parsed the body once.

Suggestion: parse the body before running guards (still skipping streaming content types), store it on the request immediately, and let the body getter return the parsed value synchronously once it is there. await req.body keeps working either way. The cost is that a request rejected by a guard has paid for the body parse first, but that is exactly what Express does with global body-parser, and guards that need the body cannot work any other way.

Fix with e2e tests is ready, PR follows. Same remark as in my other issue about the assignment rule: hope attaching the patch directly to a fresh bug report is fine.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions