Fastify plugin for ata-validator - JSON Schema validation powered by simdjson.
Drop-in replacement for Fastify's default ajv validator. Standard Schema V1 compatible.
npm install fastify-ataconst fastify = require('fastify')()
const fastifyAta = require('fastify-ata')
fastify.register(fastifyAta)
fastify.post('/user', {
schema: {
body: {
type: 'object',
properties: {
name: { type: 'string', minLength: 1 },
age: { type: 'integer', minimum: 0 },
role: { type: 'string', default: 'user' }
},
required: ['name']
}
}
}, (req, reply) => {
// req.body.role === 'user' (default applied)
reply.send({ ok: true, name: req.body.name })
})
fastify.listen({ port: 3000 })All your existing JSON Schema route definitions work as-is.
Write plain JSON Schema and get typed route handlers, no builder DSL. Add the AtaTypeProvider and author schemas with defineSchema:
import Fastify from 'fastify'
import fastifyAta from 'fastify-ata'
import { defineSchema } from 'ata-validator'
const app = Fastify().withTypeProvider<fastifyAta.AtaTypeProvider>()
await app.register(fastifyAta)
app.post('/user', {
schema: {
body: defineSchema({
type: 'object',
properties: { name: { type: 'string' }, age: { type: 'integer' } },
required: ['name'],
}),
},
}, (req, reply) => {
req.body.name // string
req.body.age // number | undefined
reply.send({ ok: true })
})defineSchema preserves the schema's literal types, so request.body, request.query, request.params, and request.headers are inferred from the schema. Same idea as @fastify/type-provider-typebox, from plain JSON Schema.
ata-validator falls back to a pure-JS engine where the native addon is not available (Cloudflare Workers, browsers, Bun), so fastify-ata runs in those environments too.
If you prefer a chainable builder over JSON Schema literals, ata-validator/t emits the same plain JSON Schema under the hood, so route schemas, the type provider, and the AOT path all keep working without an adapter. The migration from TypeBox is one import rename:
import Fastify from 'fastify'
import fastifyAta from 'fastify-ata'
import { t } from 'ata-validator/t'
const app = Fastify().withTypeProvider<fastifyAta.AtaTypeProvider>()
await app.register(fastifyAta)
const Body = t.object({
name: t.string({ minLength: 1 }),
age: t.integer({ minimum: 0 }),
email: t.optional(t.string({ format: 'email' })),
role: t.union([t.literal('admin'), t.literal('user')]),
})
app.post('/users', { schema: { body: Body } }, (req, reply) => {
req.body.name // string
req.body.email // string | undefined
req.body.role // 'admin' | 'user'
reply.send({ ok: true })
})Defaults mirror Fastify's stock validator: coerceTypes: 'array' (path params and querystring values arrive as strings and coerce to the schema types, single-element arrays collapse for querystrings) and removeAdditional: true (properties outside the schema are stripped, not rejected). Override either to opt out:
fastify.register(fastifyAta, {
coerceTypes: false, // reject "42" for integer fields instead of coercing
removeAdditional: false, // 400 on properties outside the schema
abortEarly: true, // skip detailed error collection (faster invalid path)
prettyErrors: true, // 400 message carries the ATA code + a did-you-mean
})With prettyErrors, a failed request returns a compiler-style message instead of the plain ajv text:
body must have required property 'name' [ATA7001] (did you mean `name` instead of `nme`?)
Off by default to keep the ajv-compatible message shape.
abortEarly replaces the error list with a shared stub. Good for public endpoints where only the accept/reject decision reaches the caller. On a 10-property schema the invalid path drops from roughly 15 ns/op to 3.7 ns/op.
fastify.register(fastifyAta) sets the validator compiler in the context it is registered into. Register it on the root instance and it applies everywhere; register it inside a plugin and only that subtree uses ata, while the rest of the app keeps the default validator. Use this when you want ata for some routes and the default for others, or when you are adding ata to an existing app without touching the server construction.
If you want ata to be the validator for the whole server, pass the compiler factory at construction time instead. This is the same schemaController.compilersFactory.buildValidator hook that @fastify/ajv-compiler and joi-compiler use, so the default ajv validator is never built.
const Fastify = require('fastify')
const AtaCompiler = require('fastify-ata/compiler')
const app = Fastify({
schemaController: { compilersFactory: { buildValidator: AtaCompiler() } },
})
app.post('/user', {
schema: {
body: {
type: 'object',
properties: { name: { type: 'string' }, age: { type: 'integer' } },
required: ['name'],
},
},
}, (req, reply) => reply.send({ ok: true }))The factory mirrors @fastify/ajv-compiler: it defaults to Fastify's own ajv behavior (coerceTypes: 'array', removeAdditional: true, first error only) and reads addSchema registrations for cross-schema $ref. Override through customOptions:
buildValidator: AtaCompiler() // defaults match Fastify's ajv
// per-instance overrides are read from ajv.customOptions, e.g.:
const app = Fastify({
ajv: { customOptions: { coerceTypes: false, allErrors: true } },
schemaController: { compilersFactory: { buildValidator: AtaCompiler() } },
})Note on memory: this replaces the ajv validator, so it is never instantiated. The ajv module itself can still be pulled into the process by Fastify's serializer (fast-json-stringify uses it to check serialization schemas), independent of which validator you choose. Replacing the validator removes ajv from the request validation path, not necessarily from the module graph.
const fastify = require('fastify')
const fastifyAta = require('fastify-ata')
const app = fastify({ schemaController: fastifyAta.precompiled({ dir: './.ata' }) })Each route schema gets a file under dir, named by a hash of the schema, the
validator options and the ata-validator version that wrote it. The first start
compiles a route and writes its file; the next start reads the file and compiles
nothing, and the validators go through no new Function, which is what a run
under node --disallow-code-generation-from-strings or a build with Bun's
ahead-of-time compiler needs. The files are written with the plugin's options
(coerceTypes: 'array', removeAdditional: true, as Fastify's own validator),
and the data goes through the same pass before the check, so /users/:id reads
the same integer either way. mode: 'write' compiles every route (a build step),
mode: 'read' never compiles and fails loudly on a missing file (production);
ATA_PRECOMPILE=write or read in the environment does the same. Commit the
directory or write it in CI; a changed schema or option gets a new file name,
so a stale file is never read. Fastify's router and its response serializer
(fast-json-stringify) still generate their code at startup; this covers the
validators.
Measured on Node 25 and Bun 1.4.0, 10 routes, from process start to the first validated request (medians of 15 interleaved runs): Fastify's default ajv pipeline 53.4 and 56.5 ms, fastify-ata compiling at the first request 54.0 and 53.0 ms, fastify-ata precompiled 47.6 and 46.4 ms.
Drop-in replacement for @fastify/ajv-compiler/standalone. Same API.
const StandaloneValidator = require('fastify-ata/standalone')
// Build phase (once) - compile schemas to JS files
const app = fastify({
schemaController: { compilersFactory: {
buildValidator: StandaloneValidator({
readMode: false,
storeFunction(routeOpts, code) {
fs.writeFileSync(generateFileName(routeOpts), code)
}
})
}}
})
// Read phase (every startup) - load pre-compiled, near-zero compile time
const app = fastify({
schemaController: { compilersFactory: {
buildValidator: StandaloneValidator({
readMode: true,
restoreFunction(routeOpts) {
return require(generateFileName(routeOpts))
}
})
}}
})A bulk endpoint takes thousands of records in one body. Fastify's stock parser reads the whole body into memory, parses it, and only then validates, so a bad record on line 50 of a 100 MB upload is reported after the last byte, with the whole body held in the process. fastify-ata/stream validates each record the moment it is complete and answers at the first one that fails.
const fastifyAtaStream = require('fastify-ata/stream')
await app.register(fastifyAtaStream)
app.post('/import', {
config: { records: { type: 'object', properties: { id: { type: 'integer' } }, required: ['id'] } },
}, async (req) => {
// req.body is the array of records, every one already validated
return { imported: req.body.length }
})A route that sets config.records takes its body as one JSON document per line (application/x-ndjson) or as a JSON array (application/json); the first non-blank character decides, or config.format fixes it. The first record that fails answers 400 with its index from zero, the path inside it and the errors validate() gives, under the code FST_ERR_ATA_STREAM_RECORD; a record that is not JSON answers under FST_ERR_ATA_STREAM_PARSE. The rest of the body is not read: the reply carries Connection: close and the connection is closed once it is sent. The route's bodyLimit holds, as 413. Routes without config.records keep the stock JSON parser, with its empty-body, prototype-key and broken-JSON behaviour.
With config: { records, collect: false } the handler receives only { records: count }, for a body that must never be held in memory at once; pair it with a database write per record in a later version, or use ata-validator/stream directly.
Measured on a 100 MB body of 1.3 million records sent over a real socket, Node 25, M4 (bench-stream.js):
| route | bad record at index 50 | all records valid |
|---|---|---|
stock parser, schema.body array |
400 after 564 ms, 100 MB read, +569 MB RSS | 200 in 545 ms, +557 MB RSS |
config.records |
400 after 11 ms, 1.8 MB read, +2 MB RSS | 200 in 464 ms, +332 MB RSS |
config.records, collect: false |
400 after 10 ms, 1.8 MB read, +3 MB RSS | 200 in 411 ms, +31 MB RSS |
The valid case collecting records still holds the parsed array, which is where the 332 MB goes; the count-only route holds nothing. Not covered: multipart bodies, and a record schema that needs the whole set (uniqueness across records) is not a record schema.
A form the server defines and the page validates as the user types does not need the runtime compiler in the page. fastify-ata/plans serves each schema as a plan, written once at startup with tablePlan from ata-validator/ir; the page reads it with fromPlan from ata-validator/plan and validates with the same verdicts, errors and filled defaults as new Validator(schema) on this server.
const fastifyAtaPlans = require('fastify-ata/plans')
await app.register(fastifyAtaPlans, { plans: { signup: signupSchema, order: orderSchema } })
// GET /plans/signup -> the plan, application/json, with an ETag and max-age=300// the page
import { fromPlan } from 'ata-validator/plan'
const signup = await fromPlan(await (await fetch('/plans/signup')).json())
const result = signup.validate(formData) // { valid, errors } as on the serverThe page carries the plan reader, 6.2 KB gzipped on ata-validator 1.63.1 (the entry needs 1.63.0 or later), and the format checks and error order only when a plan names them; the runtime entry with the compiler is 56 KB. fastify.ataPlan(name) gives a plan to a handler that wants to embed it in a page. Options: prefix (default /plans), richErrors (default false; a rich plan is read with ata-validator/plan-rich), assertFormat and useDefaults (default true, as the page's validator), maxAge.
A schema a plan cannot carry fails registration with its name rather than serving something that answers differently: a $ref to another document, the unevaluated keywords, dynamic references, custom keywords or formats. On ata-validator up to 1.63.1 that list also holds anyOf, oneOf, patternProperties, propertyNames, contains, dependentSchemas and a default under additionalProperties; the next ata-validator release carries them, and the plans then cover 844 of SchemaStore's 990 schemas. Serve such a schema itself and validate it with new Validator on the page.
The page and the server agree on every document only on the same ata-validator version; the plan records the version that wrote it, and fromPlan says so once when another reads it.
Nothing to add. @fastify/swagger reads the JSON Schema on each route and writes it into the document as it is, and fastify-ata validates with the same schema, so one definition serves both:
await fastify.register(require('@fastify/swagger'), { openapi: { info: { title: 'users', version: '1' } } })
await fastify.register(require('fastify-ata'))
fastify.post('/users', {
schema: {
description: 'Create a user',
body: { type: 'object', required: ['name'], properties: { name: { type: 'string', minLength: 1, description: 'Display name' } } },
response: { 201: { type: 'object', properties: { id: { type: 'string', format: 'uuid' } } } }
}
}, async (req, reply) => reply.code(201).send({ id: '...' }))
fastify.swagger() // the request body and the 201 response carry the schemas above, description and format includedChecked with fastify 5.12, @fastify/swagger 9.9 and fastify-ata 0.9.6: an invalid body is refused by ata with Fastify's usual 400, and the generated document is the route schema verbatim.
ata-validator natively implements Standard Schema V1 - the emerging standard for TypeScript-first schema libraries.
const { Validator } = require('ata-validator')
const v = new Validator(schema)
// Standard Schema V1 interface
const result = v['~standard'].validate(data)
// { value: data } on success
// { issues: [{ message, path }] } on failureWorks with Fastify v5's Standard Schema support, tRPC, TanStack Form, Drizzle ORM.
- Registers a custom
validatorCompilerusing ata-validator - Applies
defaultvalues,coerceTypes,removeAdditionalduring validation - Caches compiled schemas (WeakMap) for reuse across routes
- Returns Fastify-compatible validation errors on invalid requests (400)
- Works with Fastify v4 and v5
All numbers below are reproducible on M4 Pro / Node 25 with the benchmarks in this repo and in ata-validator/benchmark. Run-to-run noise is roughly +/- 5% at these scales.
bench-realtime.js reports about 15% more requests per second than ajv on a
50-route app whose handlers do nothing. That number is reproducible and it is also
misleading, so here is the whole picture. Sweeping the route count, echo handlers,
50 connections:
| Routes | ajv req/s | ata req/s | delta |
|---|---|---|---|
| 1 | 75,053 | 75,360 | +0.4% |
| 10 | 64,333 | 74,259 | +15.4% |
| 50 | 64,554 | 74,643 | +15.6% |
| 200 | 66,486 | 65,491 | -1.5% |
The gap is not a property of the validator, it is a dispatch effect that appears once there are enough distinct compiled validators to spoil V8's call-site caching and disappears again once there are many. Give the handler real work and it goes away entirely, one route, 50 to 200 connections:
| Per-request work | ajv req/s | ata req/s | delta |
|---|---|---|---|
| none | 75,142 | 74,989 | -0.2% |
| 1 ms | 70,342 | 71,418 | +1.5% |
| 5 ms | 33,040 | 33,016 | -0.1% |
| 20 ms | 9,310 | 9,236 | -0.8% |
profile-fastify.mjs explains why: in one request JSON.parse is 92% of the cost
and validation 7%. If your handler touches a database, the validator is not what
decides your throughput. Switch for the boot numbers below, or for the errors,
types and portability. Do not switch for requests per second.
Schema compilation at boot, from bench-startup.js. Each run takes the median of
nine process-isolated boots with a no-route Fastify baseline subtracted, so what is
left is the cost of compiling the route schemas and nothing else; the table is the
median of three such runs, on ata-validator 1.36.0 and Node 25.
| Routes | ajv | ata | delta |
|---|---|---|---|
| 50 | 45.8 ms | 2.7 ms | 17x faster |
| 100 | 83.0 ms | 4.0 ms | 21x faster |
| 250 | 149.6 ms | 8.0 ms | 19x faster |
| 500 | 267.0 ms | 14.7 ms | 18x faster |
| 1000 | 593.9 ms | 28.9 ms | 21x faster |
Total boot time, baseline included, is 69.7 ms against 627.3 ms at 1000 routes. Under about 250 routes ata's share is a few milliseconds and moves by as much between runs as the baseline does, so read the 50 and 100 rows as small rather than exact.
Fastify's documented route to the fastest startup is
@fastify/ajv-compiler in standalone mode:
compile every route schema to a file at build time, load the files at boot. The
table is process start to app.ready(), five schema types reused across routes,
median of three runs.
| Routes | ajv default | ajv standalone | ata, no build step | ata precompiled |
|---|---|---|---|---|
| 50 | 71 ms | 41 ms | 46 ms | 38 ms |
| 100 | 84 ms | 46 ms | 45 ms | 39 ms |
| 200 | 110 ms | 55 ms | 46 ms | 44 ms |
| 500 | 191 ms | 84 ms | 54 ms | 48 ms |
From about 200 routes, installing ata and doing nothing else boots faster than ajv
with the build step in place: 54 ms against 84 ms at 500 routes, on ata-validator
1.36.0. Precompiling with fastify-ata/standalone takes another 11% off, but it is
an optimization rather than the thing that makes the difference. Under 100 routes the four are close
enough that boot time should not decide anything.
| Scenario | ajv | ata | delta |
|---|---|---|---|
ReDoS pattern ^(a+)+$ |
765 ms | 0.3 ms | immune (RE2) |
Boot cost is the scenario that matters for Vercel, Fly.io and similar platforms, where a process starts far more often than a long-running box does. On a box that stays up, the gap is paid once.
For browser / edge deployments, ata ships an ata compile CLI that turns a JSON Schema into a self-contained .mjs plus TypeScript declarations.
npx ata compile schemas/user.json -o src/user.validator.mjs --name UserThe 10-field schema in ata-validator's tests/fixtures/error-dx/user.schema.json produces, on ata-validator 1.36.0, with full error detail and a schema hash:
| Variant | Raw | Gzipped |
|---|---|---|
ata runtime bundle (bun build --minify --target=browser) |
354.6 KB | 95.6 KB |
ata compile (development default, with the schema source map) |
9.2 KB | 2.6 KB |
ata compile --no-source (production default) |
7.7 KB | 2.3 KB |
ata compile --abort-early |
4.5 KB | 1.8 KB |
Generated file has zero runtime dependency on ata-validator. isValid is emitted as a TypeScript type predicate, so consumers get narrowing out of the box.
- RE2 regex - linear-time guaranteed, immune to catastrophic backtracking
- simdjson - SIMD-accelerated JSON parsing for buffer-input paths
- Multi-core -
countValid(ndjsonBuf)validates many messages in one native call - Standard Schema V1 - native support, works with Fastify v5, tRPC, TanStack Form, Drizzle
- Draft 2020-12 and Draft 7 - the full official JSON Schema Test Suite passes on ata-validator 1.36.0: 1301 of 1301 for draft 2020-12 and 929 of 929 for draft 7, in pure JS and again with code generation blocked
- Fastify's own suite - 178 of 184 tests pass with ata as the default validator; the remaining six test the default validator's private extension API rather than validation behaviour. See compat/COMPATIBILITY.md
MIT