Payload validation covers everything your API receives from clients: query parameters, headers, cookies for any method, and request bodies for POST/PUT/PATCH.
KosmoJS makes payload validation straightforward by letting you express validation rules directly through TypeScript types.
You write the type once, and it serves both as compile-time safety and runtime validation enforcement.
Validation Targets
Each target maps to a part of the incoming HTTP request.
Metadata targets (all HTTP methods):
query- URL query parameters (?page=1&limit=10)headers- HTTP request headerscookies- HTTP cookies
Body targets (POST/PUT/PATCH only):
json- JSON request bodyform- URL-encoded or multipart formraw- plain text, binary, Buffer, ArrayBuffer, Blob
Any combination of metadata targets is valid.
Body targets are mutually exclusive - one per handler.
// ✅ Multiple metadata targets + one body target
POST<{
query: { page?: number };
headers: { authorization: string };
json: { title: string };
}>
// ✅ Only metadata targets
GET<{
query: { search: string };
headers: { 'x-api-key': string };
cookies: { session: string };
}>
// ❌ Multiple body targets
POST<{
json: { title: string };
form: { title: string }; // Error: only one body target allowed
}>
// ❌ Body target on GET
GET<{
json: { data: string }; // Error: GET cannot have request body
}>Invalid configurations are detected at dev time and disabled automatically.
Coerced values
Everything off the wire is a string. Some primitive values are coerced automatically, when typed accordingly and content is appropriate.
Numbers - coerced in route params and query.
Typing a field as number turns "10" into 10.
GET<{
query: { page?: number; }; // coerced: "2" -> 2
}>Booleans - coerced in query only.
Typing a field as boolean turns "true"/"false" into true/false.
GET<{
query: { draft?: boolean; }; // coerced: "true" -> true
}>Params are path segments where a boolean is meaningless, so they never coerce booleans.
Coercion only maps the exact expected forms:
- a
numberfield coerce only numeric values - a
booleanfield coerce only"true"/"false"values
Everything else stays a string and fails validation cleanly.
headers/cookies/form/raw never coerce.
json carries real numbers and booleans natively, no coercion needed.
Basic Payload Validation
Pass the payload type as the first type argument to your method handler:
import { defineRoute } from "_/api";
export default defineRoute<"posts">(({ POST }) => [
POST<{
json: {
title: VRefine<string, { minLength: 1, maxLength: 255 }>;
content: string;
tags: string[];
isPublished: boolean;
scheduledPublishAt?: VRefine<string, { format: "date-time" }>;
},
}>(async (ctx) => {
const { title, content, tags } = ctx.validated.json;
}),
]);Optional fields (?) can be omitted entirely. When present, they must still pass their type and refinement constraints.
Notice how VRefine is used to add validation constraints to specific fields.
The minLength and maxLength constraints ensure titles aren't empty or excessively long.
The format: "date-time" constraint leverages JSON Schema's format validation to ensure dates are properly formatted.
Without VRefine, fields are validated only for their basic type - a string must be a string, an array must be an array, but no additional constraints apply.
Complex Nested Structures
Since validation rules are just TypeScript types, nested objects, union types, conditional fields, referenced types - all work naturally:
import type { BillingAddress } from "~/types/checkout";
type PaymentMethod = {
type: "card" | "wallet";
card?: {
number: VRefine<string, { pattern: "^[0-9]{13,19}$" }>;
expMonth: VRefine<number, { minimum: 1, maximum: 12 }>;
expYear: number;
cvc: VRefine<string, { pattern: "^[0-9]{3,4}$" }>;
holderName: string;
};
wallet?: {
walletId: string;
token: VRefine<string, { minLength: 1, maxLength: 500 }>;
};
};
type Payload = {
orderId: VRefine<string, { pattern: "^[a-zA-Z0-9_-]{1,50}$" }>;
amount: VRefine<number, { minimum: 0.01, maximum: 1000000 }>;
currency: VRefine<string, { pattern: "^[A-Z]{3}$" }>;
paymentMethod: PaymentMethod;
billingAddress: BillingAddress;
};
export default defineRoute<"checkout">(({ POST }) => [
POST<{
json: Payload,
}>(async (ctx) => {
// every field validated before handler runs
}),
]);Undeclared Properties
A json or form payload accepts the properties its type declares and nothing else. An extra field fails validation with a 400 before the handler runs, so a payload spread into a database update cannot write a column the type never mentioned:
// json: { name: string; email: string }
{ "name": "Ann", "email": "ann@example.com", "role": "admin" }
// -> 400 ValidationError, target "json": should not have additional property "role"This holds at every depth: nested objects, array and tuple elements, the values of records, index signatures and mapped types, and the result of Partial, Pick, Omit, Required and Readonly. An intersection is checked as a whole: Base & Extra accepts the properties of both, and rejects anything neither declares.
query, headers and cookies stay open - browsers, proxies and analytics add parameters and headers no route declares, and rejecting them would turn ordinary traffic into errors. raw is not an object. Responses are closed the same way as payloads.
To accept extra properties in a json or form payload, say so on the object:
type Payload = {
name: string;
// anything else goes through
meta: VRefine<{ source: string }, { additionalProperties: true }>;
};For keys not known in advance, use Record<string, T> or { [key: string]: T }. Either one accepts any key, while each value is still checked against T.
For an intersection, VRefine<A & B, { unevaluatedProperties: true }> reopens it as a whole, and additionalProperties: true on one of its members reopens it as well.
The opposite holds too: additionalProperties: false on a member closes it on its own, and then it rejects the properties of every other member - leave members unrefined and let the intersection be closed as a whole.
HTML forms
A plain HTML form often posts fields the route never declares: the name of the clicked submit button, a CSRF token added by middleware, a _method override. A closed form payload rejects each of them with a 400.
Declare the fields you expect, or reopen the payload when the form is not yours to shape:
POST<{
form: VRefine<{ title: string; body: string }, { additionalProperties: true }>;
}>Combining Multiple Targets
You can validate multiple parts of the request simultaneously by specifying multiple targets. This is particularly useful for endpoints that need to validate query parameters, headers, and request body together:
export default defineRoute<"posts/search">(({ POST }) => [
POST<{
query: {
page: VRefine<number, { minimum: 1 }>;
limit: VRefine<number, { minimum: 1, maximum: 100 }>;
sortBy?: "date" | "title" | "views";
};
headers: {
authorization: VRefine<string, { pattern: "^Bearer .+" }>;
"x-api-version"?: string;
};
cookies: {
session: string;
};
json: {
filters: {
tags?: string[];
status?: "draft" | "published" | "archived";
dateRange?: {
from: VRefine<string, { format: "date-time" }>;
to: VRefine<string, { format: "date-time" }>;
};
};
};
}>(async (ctx) => {
const { page, limit, sortBy } = ctx.validated.query;
const { authorization } = ctx.validated.headers;
const { session } = ctx.validated.cookies;
const { filters } = ctx.validated.json;
}),
]);Each target is validated independently. All must pass before your handler executes.
Body Formats
JSON
POST<{
json: {
name: string;
email: VRefine<string, { format: "email" }>;
};
}>(async (ctx) => {
const { name, email } = ctx.validated.json;
})Form (URL-encoded)
POST<{
form: {
username: VRefine<string, { minLength: 3, maxLength: 20 }>;
password: VRefine<string, { minLength: 8 }>;
};
}>(async (ctx) => {
const { username, password } = ctx.validated.form;
})Multipart (file uploads)
POST<{
form: {
file: File;
title: string;
description?: string;
};
}>(async (ctx) => {
const { file, title, description } = ctx.validated.form;
})Raw
POST<{
raw: VRefine<string, { minLength: 1, maxLength: 10000 }>;
}>(async (ctx) => {
const rawContent = ctx.validated.raw;
})Worth noting: you can only specify one body target per handler (json, form or raw), but you can combine it with any number of metadata targets (query, headers, cookies).
Referenced Types
As your application grows, defining complex types inline becomes unwieldy. You'll want to define types once and reuse them across multiple routes.
KosmoJS fully supports this pattern - you can define types in separate files, import them where needed, and use them for validation just like inline types.
Suppose you have a file defining user-related types:
export type UserProfile = {
name: VRefine<string, { minLength: 1, maxLength: 255 }>;
email: VRefine<string, { format: "email" }>;
};
export type UserPreferences = {
theme: "light" | "dark";
notifications: NotificationPreferences;
};
type NotificationPreferences = {
enabled: boolean;
};import type { UserProfile, UserPreferences } from "./user";
export type Payload<T> = {
data: T;
meta: {
pagination?: { page: number; limit: number; total: number };
cache: { ttl: number; revalidate: boolean };
};
};
export type User = {
id: number;
profile: UserProfile;
preferences: UserPreferences;
posts: Post[];
};
export type Post = {
id: VRefine<number, { minimum: 1, multipleOf: 1 }>;
title: string;
tags: { id: string; name: string }[];
stats?: { views: number; likes: number };
};Now you can use these types in any route by importing them:
import type { User, Payload } from "~/types/api-payload";
import { defineRoute } from "_/api";
export default defineRoute<"users">(({ POST }) => [
POST<{
json: Payload<User>,
}>(async (ctx) => {
// ctx.validated.json typed as Payload<User>
}),
]);Generics are resolved and every referenced type traced, producing a complete validation schema. Update a shared type and validation updates everywhere it's used.
Different routes, same wrapper:
import type { Post, Payload } from "~/types/api-payload";
export default defineRoute<"posts">(({ POST }) => [
POST<{
json: Payload<Post>,
}>(async (ctx) => {}),
]);What Resolves
Types are read from the source, the way your editor reads them, and followed across files:
- named, default and namespace imports (
import type * as T, thenT.User), aliased imports, re-exports andexport *, and the~/,@/,_/,#src/and#lib/path aliases; - interfaces and
extends, generics,Partial,Pick,Omitand the other utility types, mapped, conditional, indexed and template literal types; - recursive types, such as a tree whose nodes hold their children - validated at any depth;
- enums, as the union of their values;
Role.Adminnames a single member.
What needs the type checker does not resolve: a type built from a value with typeof, or one a library computes, like an ORM's row type derived from a table. Write those shapes out, or describe them with a type of your own. A type that does not resolve is reported when the route is built. Details ›
Overriding the Default
Every target has its own slot: validate:json, validate:form, validate:raw.
Claim one and your middleware runs instead of the built-in validator. Use it for a body format no schema describes, or a check that has to hit the database.
Replacing one target leaves the rest alone. And ctx.bodyparser.<target>() is cached, so your validator and your handler can both read the body. Details ›