@playstack/validation
Zod-backed shared schemas and one portable HTTP validation-error contract.
Reference: @playstack/validation@0.1.0-beta.5 · TypeScript · MIT licence
Free. MIT licensed. Check preview availability before installing. See package access.
@playstack/validation lets browser forms, APIs, and generated OpenAPI descriptions agree on schemas and validation failures.
Install
npm install @playstack/core @playstack/validation zodSelect only the framework requirements you use:
pnpm exec playstack add validation --dry-run --json
pnpm exec playstack add validation --api=apps/api --dry-run --json
pnpm exec playstack add validation --api=apps/api --adapter=openapi --dry-run --jsonPortable and web-only adoption select no Nest packages. --api selects native
Nest requirements for /nest/pipe; the explicit openapi adapter requires an API
target and follows the application's Nest major: Swagger and nestjs-zod for /nest
on Nest 10/11, or Swagger 12 alone for /nest-native on Nest 12.
Existing dependencies are left in place; the CLI does not remove Swagger from
applications that already use it.
Compose one schema across boundaries
Keep schemas in an application contract library, parse at the transport edge, and pass only validated values to domain code.
import { emailSchema, parse, z } from '@playstack/validation'
export const createUserSchema = z.object({
email: emailSchema,
displayName: z.string().trim().min(1).max(80),
})
export type CreateUserInput = z.output<typeof createUserSchema>
export function createUser(input: unknown) {
const command = parse(createUserSchema, input)
return users.create(command)
}Stable wire contract
formatValidationError and validationBodyFromError produce the same response shape for every HTTP framework:
interface ValidationErrorBody {
error: { code: string; retryable: boolean; message: string }
fields: Readonly<Record<string, readonly string[]>>
form: readonly string[]
}fields uses dot-separated schema paths. Issues without a path go in form. malformedJsonErrorBody() and refinementFailedErrorBody() produce the smaller standard error body.
Configuration reference
The portable package has no global configuration. Parsing functions accept an optional Zod error map:
| API | Input | Result |
|---|---|---|
parse(schema, input, options?) | Any synchronous Zod schema | Validated output or ValidationFailedError. |
parseAsync(schema, input, options?) | Schema with async refinements | Validated output or ValidationFailedError. |
formatValidationError(error, message?) | A ZodError | Portable ValidationErrorBody. |
validationBodyFromError(error) | ValidationFailedError | Portable ValidationErrorBody. |
Built-in schemas cover normalized email, kebab-case slugs, offset ISO timestamps, sort direction, and cursor pagination with a default limit of 25 and maximum of 100.
NestJS bridge
For schema validation without DTO/OpenAPI helpers, use the native leaf:
import { PlaystackValidationPipe } from '@playstack/validation/nest/pipe'This entry point requires @nestjs/common and its required peers, alongside the
package's ordinary runtime dependencies. Its JavaScript and declaration graphs
do not load nestjs-zod or Swagger. Async refinements, error-map options and
HTTP error responses have the same behavior through either Nest entry point.
The complete /nest bridge reexports that same pipe class plus the DTO and
serializer helpers; install its optional nestjs-zod and Swagger peers when
using that path:
import {
PlaystackValidationPipe,
cleanupOpenApiDoc,
createZodDto,
} from '@playstack/validation/nest'
class CreateUserDto extends createZodDto(createUserSchema) {}
@Post()
create(
@Body(new PlaystackValidationPipe(createUserSchema)) input: CreateUserInput,
) {
return users.create(input)
}
const document = cleanupOpenApiDoc(SwaggerModule.createDocument(app, config))PlaystackValidationPipe accepts the schema and the same optional error-map configuration. Zod issues become HTTP 400 responses; unexpected refinement failures become HTTP 500 responses. DTO and serializer helpers are re-exported from nestjs-zod so request, response, and OpenAPI schemas remain aligned.
Nest 12 native OpenAPI path
nestjs-zod supports Nest 10 and 11 only. On @nestjs/common 12, import
@playstack/validation/nest-native instead of /nest: it uses Nest 12's
StandardSchemaValidationPipe, StandardSchemaSerializerInterceptor and Swagger
12's Standard Schema conversion, and never loads nestjs-zod. Each entry point
refuses the other Nest generation at load with a message naming the entry point to
use. playstack add validation --api --adapter=openapi picks the path from the
application's installed (else declared) @nestjs/common major and reports the
choice; --adapter=openapi-native selects the Nest 12 path explicitly.
import { StandardSchemaSerializerInterceptor } from '@nestjs/common'
import { APP_INTERCEPTOR, APP_PIPE } from '@nestjs/core'
import { createPlaystackSchemaValidationPipe } from '@playstack/validation/nest-native'
import { ApiSchemaResponse } from '@playstack/validation/nest-native/openapi'
const CreateUser = createUserSchema.meta({ id: 'CreateUser' })
@Post()
@ApiSchemaResponse({ status: 201, schema: User })
create(@Body({ schema: CreateUser }) input: z.output<typeof CreateUser>) {
return users.create(input)
}
// Module providers:
{ provide: APP_PIPE, useValue: createPlaystackSchemaValidationPipe({ formatError }) },
{ provide: APP_INTERCEPTOR, useClass: StandardSchemaSerializerInterceptor },createPlaystackSchemaValidationPipe() extends the native pipe with the Playstack
400 body, formatError, Zod error maps and the safe 500 for a refinement that
throws or rejects. It parses Zod schemas once with safeParseAsync; Zod's Standard
Schema validate would run an asynchronous refinement twice. Parameters carry their
schema with @Body({ schema }), @Query({ schema }) or @Param('id', { schema }),
which Swagger documents too. ApiSchemaResponse documents a response and, unless
serialize: false, serializes the result through the same schema; pass isArray: true
with the item schema for array responses, because the native serializer validates
arrays item by item.
Migrating from /nest:
/nest (nestjs-zod) | Nest 12 |
|---|---|
createZodDto(schema) DTO class | @Body({ schema }) with z.output<typeof schema>; name components with .meta({ id }) |
ZodResponse({ status, type }) | ApiSchemaResponse({ status, schema, isArray? }) |
ZodSerializerDto(dto) | @SerializeOptions({ schema }) from @nestjs/common |
ZodSerializerInterceptor | StandardSchemaSerializerInterceptor from @nestjs/common |
cleanupOpenApiDoc(document) | Not needed: Swagger 12 emits OpenAPI 3.0 components directly |
The native document is OpenAPI 3.0 (nullable: true, boolean exclusiveMinimum,
literals as enum); cleanupOpenApiDoc could emit 3.1. An application that needs
3.1 output supplies its own standardSchemaConverter to SwaggerModule.createDocument.
React bridge
applyValidationErrors works with any form library that exposes a setError(path, { type, message }) callback:
import { applyValidationErrors } from '@playstack/validation/react'
const { fieldCount, form } = applyValidationErrors(response, setError)
setFormErrors(form)It returns the number of field messages applied plus the form-level messages; it does not choose a React form library or render error UI.
Boundary
Validation is not a sanitizer, form library, localization framework, authorization layer, or database-schema generator. The application owns schema placement, localized error maps, and transport-specific parsing of malformed JSON.
API entry points and requirements
Reference snapshot: @playstack/validation@0.1.0-beta.5. Import only the entry point your runtime needs. Paths below are relative to the installed package; use Go to Definition in your editor to inspect exact parameters, return types and overloads. Do not import the declaration-file paths directly.
| Public entry point | Declaration file |
|---|---|
@playstack/validation | ./dist/index.d.ts |
@playstack/validation/errors | ./dist/errors.d.ts |
@playstack/validation/nest | ./dist/nest.d.ts |
@playstack/validation/nest/pipe | ./dist/nest/pipe.d.ts |
@playstack/validation/nest-native | ./dist/nest-native.d.ts |
@playstack/validation/nest-native/openapi | ./dist/nest-native/openapi.d.ts |
@playstack/validation/react | ./dist/react.d.ts |
@playstack/validation/package.json | No TypeScript declaration (asset or metadata export). |
Node.js engine requirement: >=20. This is not a claim that every entry point works in browsers or Workers.
Peer dependencies
Keep existing framework versions that satisfy these ranges. Install optional peers only when using the corresponding adapter. The package manager resolves ordinary dependencies separately.
| Peer | Compatible range | When needed |
|---|---|---|
@nestjs/common | ^10.0.0 || ^11.0.0 || ^12.0.0 | Optional; only for the entry points that use it. |
@nestjs/swagger | ^7.4.2 || ^8.0.0 || ^11.0.0 || ^12.0.0 | Optional; only for the entry points that use it. |
nestjs-zod | ^5.5.0 | Optional; only for the entry points that use it. |
For a complete first program, start with Getting started. For API lookup and partial-example conventions, see Reading the reference. Provider failures, lifecycle requirements and application responsibilities remain described in the guide above; types alone do not establish production safety.