In NestJS 12, how does StandardSchemaValidationPipe validate @Body({ schema }), and what happens if the pipe is never registered?
answer
- metadata versus enforcement
- the schema rides on ArgumentMetadata
- a validate call and its issues
- output replaces input by default
- no schema, no check
basics
~20 sIn NestJS 12, @Body({ schema }) only attaches the schema as metadata. StandardSchemaValidationPipe reads it, calls the schema's ~standard.validate, throws a 400 listing path-prefixed issues, and passes the schema's output on. Without the pipe registered, nothing validates.
solid answer
~40 sNest 12 added a `schema` option to `@Body()`, `@Query()`, `@Param()` and `@RawBody()`, and to the gateway and microservice payload decorators. On its own it only attaches a Standard Schema object, such as a Zod object, to the parameter's `ArgumentMetadata`. The built-in `StandardSchemaValidationPipe`, usually bound with `app.useGlobalPipes()`, reads `metadata.schema`, calls the schema's `~standard.validate()` and, if issues come back, throws a 400 whose `message` lists each issue, prefixed with its path when it has one, like `quantity: Too small: expected number to be >=1`. On success it returns the schema's output by default (`transform: true`), so coercion and defaults reach the handler. Parameters with no schema pass through untouched, which makes global binding safe; custom decorators are skipped unless `validateCustomDecorators` is set. Forget to register the pipe and the endpoint accepts anything.
code
typescript · 16 linesimport { Body, Controller, Post } from '@nestjs/common';
import { z } from 'zod';
const createOrderSchema = z.object({
productId: z.coerce.number().int().positive(),
quantity: z.number().int().min(1),
});
type CreateOrderInput = z.infer<typeof createOrderSchema>;
@Controller('orders')
export class OrdersController {
@Post()
create(@Body({ schema: createOrderSchema }) input: CreateOrderInput) {
return input;
}
}go deeper
Recall that Nest 12 lets @Body() carry a schema, and that StandardSchemaValidationPipe must be registered for that schema to be checked.
Explain the split between decorator metadata and the pipe, the transform default, the path-prefixed messages, and why no-schema parameters pass through.
Show you would catch an unregistered pipe in tests, enable validateCustomDecorators where needed, and set unknown-key policy in each schema rather than in the pipe.
Weigh running both pipes globally during an incremental move, and which error contract and unknown-key convention the team fixes before endpoints migrate.
## Two halves: the decorator and the pipe **Standard Schema** is a small shared interface that schema libraries implement: every compliant schema exposes a `~standard` property with a `validate()` function returning either a value or a list of issues. Nest 12 builds on it in two separate pieces: - **The `schema` option** on parameter decorators: `@Body({ schema })`, `@Query('page', { schema })`, `@Param('id', { schema })`, `@RawBody({ schema })`, plus `@MessageBody()` in gateways and `@Payload()` in microservices. Custom decorators made with `createParamDecorator()` accept it too. The decorator records the schema in the parameter's metadata, and it reaches every pipe as `ArgumentMetadata.schema`. - **`StandardSchemaValidationPipe`**, exported from `@nestjs/common`, which enforces it. The migration guide is explicit that the decorator on its own only attaches schema metadata. If no pipe reads it, a body that breaks the schema reaches the handler untouched, and the existing `ValidationPipe` does not read `schema` either. ## What the pipe does, step by step 1. It reads `metadata.schema`. With no schema, or for a custom-decorator argument while `validateCustomDecorators` is off, it returns the value unchanged. 2. It strips prototype-pollution keys (`__proto__`, `prototype`, `constructor`) from the value. 3. It calls `schema['~standard'].validate(value, validateOptions)` and awaits the result, so asynchronous schemas work. 4. If the result has `issues`, it calls `exceptionFactory(issues)` and throws what that returns. The default factory builds the exception for `errorHttpStatusCode` (400 by default) with a `message` array; each issue with a path is written as `path: message`, path segments joined with dots, as in `items.1.quantity: ...`. 5. Otherwise it returns `result.value`, the schema's **output**, when `transform` is `true` (the default), or the original input when `transform` is `false`. ## Options | Option | Default | Purpose | |---|---|---| | `transform` | `true` | Return the schema's output (coerced, defaulted) instead of the raw input | | `validateCustomDecorators` | `false` | Also validate arguments from `createParamDecorator()` decorators | | `validateOptions` | none | Forwarded to `~standard.validate()` for libraries that accept options | | `errorHttpStatusCode` | 400 | Status of the default exception | | `exceptionFactory` | built-in | Receives the issue list and returns the exception to throw | ## What the schema decides, not the pipe The pipe has no `whitelist` option. How unknown properties are handled is the schema's own policy; with Zod, for example: - `z.object()` strips unknown keys, much like `whitelist`; - `z.strictObject()` rejects them, failing with `Unrecognized key: "isAdmin"`; - `z.looseObject()` keeps them. Coercion lives in the schema too. Path and query values always arrive as strings, so `@Param('id', { schema: z.coerce.number().int().positive() }) id: number` converts before validating, and the handler gets a number because `transform` defaults to `true`. With `transform: false`, the handler gets the original input, so its parameter should be typed with the schema's input type. ## Registering it, and living beside ValidationPipe ```typescript // main.ts app.useGlobalPipes(new ValidationPipe({ whitelist: true }), new StandardSchemaValidationPipe()); // orders.controller.ts @Post() create(@Body({ schema: createOrderSchema }) input: CreateOrderInput) { return this.ordersService.create(input); } ``` Both pipes can be global at once. `ValidationPipe` validates only parameters typed with a class, and `StandardSchemaValidationPipe` validates only parameters that declare a schema, so a codebase can adopt schemas one endpoint at a time. A parameter typed with a schema-inferred type, which is a type alias rather than a class, gives `ValidationPipe` nothing to validate. ## Reading a failure With the default factory, a create-order body whose `quantity` is `0` produces: ```json { "message": ["quantity: Too small: expected number to be >=1"], "error": "Bad Request", "statusCode": 400 } ``` The text after the path comes from the schema library, so its wording differs between libraries and from class-validator's. Change the status with `errorHttpStatusCode`, or the whole body with `exceptionFactory`, which receives every issue with its `message` and `path`. Common mistakes: - adding `{ schema }` everywhere but never registering the pipe; - expecting a custom decorator's schema to run without `validateCustomDecorators: true`; - setting `transform: false` while still typing the parameter with the schema's output type.
- How do you make a schema validation failure answer 422 with your own body shape?For the status alone, pass `errorHttpStatusCode: 422`. To control the body, pass `exceptionFactory`, which receives the issue list; map each issue's `path` (segments that are keys or objects with a `key`) and `message`, and return an `UnprocessableEntityException` carrying that structure. What the body should contain is an API-design decision beyond the pipe.
- Does StandardSchemaValidationPipe run a schema attached to a custom decorator created with createParamDecorator()?Only when the pipe is constructed with `validateCustomDecorators: true`. Custom decorators accept the `schema` option, but by default the pipe returns custom-decorator arguments untouched, so a tenant header validated through a custom `@TenantId({ schema })` decorator is not checked until that option is set.
- Adding { schema } to @Body() validates the body on its own
- StandardSchemaValidationPipe rejects parameters that declare no schema
- The pipe strips unknown keys through a whitelist option of its own
- By default the handler receives the raw input rather than the schema's output
- A global ValidationPipe also enforces the schema option
Assumes NestJS 12, which added the schema option on parameter decorators and the built-in StandardSchemaValidationPipe; earlier majors had neither.