JSON 15 ๐ Programmatic Schema Compilation and Validation (Ajv)
Ajv is the JSON Schema validator that compiles a schema into a JavaScript function. The compilation is the mechanism that makes the validation fast: instead of interpreting the schema on every validation call, Ajv generates the code that performs the checks, and the generated function is what runs on the data. The Ajv documentation states this directly: “Ajv takes a schema for your JSON data and converts it into a very efficient JavaScript code that validates your data according to the schema” . The compilation happens once, and the compiled function is reused for every subsequent validation of the same schema.
The library is the most widely used JSON Schema validator in the JavaScript ecosystem, and it supports the multiple specification drafts. The default export supports draft-07 (and draft-06), the ajv/dist/2019 export supports draft 2019-09, the ajv/dist/2020 export supports draft 2020-12, and the ajv/dist/jtd export supports the JSON Type Definition (RFC 8927) . The draft choice is the import choice, and the import is the mechanism that determines which keywords are available.
Key point: Ajv compiles a schema into a validation function with ajv.compile(schema). The compiled function is a type guard, and the validate.errors array contains the failure details when the data is invalid. The compilation is cached, and the same schema object returns the same compiled function. The draft support is the import choice: the default for draft-07, the ajv/dist/2019 for 2019-09, and the ajv/dist/2020 for 2020-12.
Why Ajv exists
The interpretation problem. A validator that interprets the schema on every validation call re-reads the keywords, re-resolves the references, and re-builds the comparison logic for each piece of data. The interpretation is the correct behaviour, but it is slow for the high-throughput APIs. Ajv’s compilation is the mechanism that moves the work to the compile time: the schema is parsed once, the code is generated once, and the validation is the generated function call . The speed is the primary reason the library exists, and the benchmarks place it at the top of the JSON Schema validators.
The draft support problem. The JSON Schema specification has the multiple drafts, and the projects are on the different drafts. Ajv’s default export is the draft-07 support, and the separate exports are the 2019-09 and the 2020-12 support. The separate export is the mechanism that keeps the draft-07 users from paying the bundle and the generated-code cost of the newer features . The 2019-09 and the 2020-12 featuresโthe unevaluatedProperties, the unevaluatedItems, the dependentRequired, the dependentSchemas, and the dynamic referencesโrequire the separate import, and the import is the mechanism that opts into the cost.
The TypeScript problem. Ajv’s TypeScript support is the mechanism that makes the compiled function a type guard. The ajv.compile<MyData>(schema) or the JSONSchemaType<MyData> annotation makes the validate(data) narrow the data type to MyData after the successful validation . The type guard is the mechanism that connects the runtime validation to the compile-time type, and the connection is the reason the TypeScript projects use Ajv.
The error problem. The validation function returns a boolean, and the validate.errors array holds the failure details. The errors are the open union, and the DefinedError type is the cast that makes the error handling type-safe . The keyword property is the tag, and the switch on the keyword is the mechanism that handles the specific error type.
The caching problem. The compilation is relatively slow, and the validation is very fast. The Ajv documentation states that the compiled functions are cached, and the same schema object returns the same compiled function . The caching is the mechanism that keeps the compilation cost to the once-per-schema, and the cache is the reason the repeated validation is the fast path.
a. The basic compilation and the validation
The basic flow is the three steps: the Ajv instance, the schema, and the compiled function. The new Ajv() creates the instance, the schema object is the definition, and the ajv.compile(schema) returns the validation function.
// The basic compilation
const Ajv = require("ajv");
const ajv = new Ajv(); // The options can be passed, e.g. { allErrors: true }
const schema = {
type: "object",
properties: {
foo: { type: "integer" },
bar: { type: "string" },
},
required: ["foo"],
additionalProperties: false,
};
// The compile returns the validation function.
const validate = ajv.compile(schema);
const data = { foo: 1, bar: "abc" };
// The validate returns the boolean.
const valid = validate(data);
if (!valid) {
// The validate.errors holds the failure details.
console.log(validate.errors);
}
The validate function is the compiled code, and the validate(data) call is the fast path. The validate.errors is the array of the failure details, and it is overwritten on every call . The overwrite is the mechanism that the documentation warns about: the errors array reference must be copied if it is needed later, because the next validation call replaces the contents .
The ajv.validate(schema, data) is the shorthand that compiles the schema on the first call and validates the data. The shorthand is the convenience, but the documentation recommends the compile for the performance, because the shorthand re-checks the schema on every call . The compile is the mechanism that makes the compilation explicit, and the explicit compilation is the mechanism that keeps the validation fast.
// The shorthand
const valid = ajv.validate(schema, data);
if (!valid) console.log(ajv.errors);
// The compile (recommended for the performance)
const validate = ajv.compile(schema);
const validCompiled = validate(data);
if (!validCompiled) console.log(validate.errors);
b. The draft selection and the TypeScript integration
The draft selection is the import choice. The default export is the draft-07, and the ajv/dist/2019 and the ajv/dist/2020 are the newer drafts. The 2019-09 and the 2020-12 features are the unevaluatedProperties, the unevaluatedItems, the dependentRequired, the dependentSchemas, and the dynamic references .
// The draft-07 (default)
import Ajv from "ajv";
const ajv = new Ajv();
// The 2019-09 and the 2020-12
import Ajv2019 from "ajv/dist/2019";
const ajv2019 = new Ajv2019();
// The 2020-12 (the specific export)
import Ajv2020 from "ajv/dist/2020";
const ajv2020 = new Ajv2020();
The ajv/dist/2019 export supports the 2019-09 features, and the ajv/dist/2020 export supports the 2020-12 features. The 2019-09 support is the separate export because the features add the generated code even when they are not used, and the separation is the mechanism that keeps the draft-07 users from the cost . The ajv/dist/2020 is the specific 2020-12 export, and it is the import for the project that uses the prefixItems and the $defs.
The TypeScript integration is the JSONSchemaType utility. The type is the annotation on the schema, and the ajv.compile infers the type guard from the annotation.
// The TypeScript type guard
import Ajv, { JSONSchemaType } from "ajv";
interface MyData {
foo: number;
bar?: string;
}
const schema: JSONSchemaType<MyData> = {
type: "object",
properties: {
foo: { type: "integer" },
bar: { type: "string", nullable: true },
},
required: ["foo"],
additionalProperties: false,
};
const ajv = new Ajv();
// The validate is a type guard for MyData.
const validate = ajv.compile(schema);
const data = { foo: 1, bar: "abc" };
if (validate(data)) {
// The data is MyData here.
console.log(data.foo);
} else {
console.log(validate.errors);
}
The JSONSchemaType<MyData> is the annotation that makes the schema type-checked, and the ajv.compile(schema) infers the validate as the type guard . The nullable: true is the Ajv-specific extension for the nullable fields, and it is the mechanism that makes the TypeScript type match the schema. The strictNullChecks must be true for the type guard to work correctly .
The DefinedError is the type for the error handling. The validate.errors is the open union, and the cast to DefinedError[] is the mechanism that makes the switch on the keyword type-safe.
// The type-safe error handling
import { DefinedError } from "ajv";
if (!validate(data)) {
for (const err of validate.errors as DefinedError[]) {
switch (err.keyword) {
case "type":
// The err.params.type is the expected type.
console.log(err.params.type);
break;
case "required":
// The err.params.missingProperty is the missing field.
console.log(err.params.missingProperty);
break;
}
}
}
The keyword is the tag, and the params is the error-specific data. The type keyword’s params has the expected type, and the required keyword’s params has the missing property . The type-safe handling is the mechanism that makes the error display specific, and the specific display is the reason the user sees the actionable message.
Complete Example Session
// ============================================
// PART 1: THE BASIC COMPILATION
// ============================================
const Ajv = require("ajv");
const ajv = new Ajv();
const schema = {
type: "object",
properties: {
foo: { type: "integer" },
bar: { type: "string" },
},
required: ["foo"],
additionalProperties: false,
};
const validate = ajv.compile(schema);
// ============================================
// PART 2: THE VALID DATA
// ============================================
const validData = { foo: 1, bar: "abc" };
const isValid = validate(validData);
// The isValid is true.
// The validate.errors is null.
// ============================================
// PART 3: THE INVALID DATA
// ============================================
const invalidData = { bar: "abc" };
const isInvalid = validate(invalidData);
// The isInvalid is false.
// The validate.errors holds the failure details.
// ============================================
// PART 4: THE ERROR ACCESS
// ============================================
if (!validate(invalidData)) {
console.log(validate.errors);
// The errors is the array of the failure details.
// The errors is overwritten on the next call.
}
// ============================================
// PART 5: THE ALL ERRORS OPTION
// ============================================
const ajvAll = new Ajv({ allErrors: true });
// The allErrors: true collects every failure.
// The default is the first failure.
// ============================================
// PART 6: THE DRAFT SELECTION
// ============================================
import Ajv2020 from "ajv/dist/2020";
const ajv2020 = new Ajv2020();
const schema2020 = {
type: "object",
properties: { foo: { type: "integer" } },
required: ["foo"],
unevaluatedProperties: false,
};
const validate2020 = ajv2020.compile(schema2020);
// The 2020-12 export supports the unevaluatedProperties.
// ============================================
// PART 7: THE TYPESCRIPT TYPE GUARD
// ============================================
// The JSONSchemaType annotation
const schemaTyped: JSONSchemaType<MyData> = {
type: "object",
properties: {
foo: { type: "integer" },
bar: { type: "string", nullable: true },
},
required: ["foo"],
additionalProperties: false,
};
const validateTyped = ajv.compile(schemaTyped);
// ============================================
// PART 8: THE TYPE-SAFE ERROR HANDLING
// ============================================
import { DefinedError } from "ajv";
if (!validateTyped(data)) {
for (const err of validateTyped.errors as DefinedError[]) {
switch (err.keyword) {
case "type":
console.log(err.params.type);
break;
case "required":
console.log(err.params.missingProperty);
break;
}
}
}
// ============================================
// PART 9: THE SHORTHAND
// ============================================
const valid = ajv.validate(schema, data);
if (!valid) console.log(ajv.errors);
// The shorthand compiles on the first call and validates.
// The compile is the explicit and the faster path.
// ============================================
// PART 10: THE CHECKLIST
// ============================================
// [ ] The Ajv instance is created.
// [ ] The schema is the plain object.
// [ ] The compile returns the validate function.
// [ ] The validate.errors holds the failure details.
// [ ] The allErrors: true collects every failure.
// [ ] The draft export is chosen for the schema draft.
// [ ] The JSONSchemaType is the TypeScript annotation.
// [ ] The DefinedError is the type-safe error handling.
The ten parts covered the basic compilation, the valid data, the invalid data, the error access, the allErrors option, the draft selection, the TypeScript type guard, the type-safe error handling, the shorthand, and the checklist. The through-line is that the compilation is the fast path, and the type guard is the TypeScript integration.
Quick Reference
The Ajv API
| API | Purpose |
|---|---|
new Ajv(options) | Create the instance |
ajv.compile(schema) | Compile the schema to the validate function |
validate(data) | Validate the data, return the boolean |
validate.errors | The failure details, overwritten per call |
ajv.validate(schema, data) | The shorthand, compile and validate |
ajv.addSchema(schema) | Register the external schema |
ajv.addFormat(name, format) | Add the custom format |
ajv.addKeyword(definition) | Add the custom keyword |
The draft exports
| Draft | Import |
|---|---|
| draft-07 (default) | import Ajv from "ajv" |
| draft 2019-09 | import Ajv2019 from "ajv/dist/2019" |
| draft 2020-12 | import Ajv2020 from "ajv/dist/2020" |
| JTD | import Ajv from "ajv/dist/jtd" |
The TypeScript types
| Type | Purpose |
|---|---|
JSONSchemaType<T> | The type-checked schema |
DefinedError | The type-safe error union |
| The type guard | The validate(data) narrows the data |
The common options
| Option | Purpose |
|---|---|
allErrors | Collect every failure |
strict | The strict mode |
useDefaults | Assign the defaults |
coerceTypes | Coerce the data to the type |
Best Practices
โ Do This:
// Use the compile for the performance
const validate = ajv.compile(schema); // โ
// Copy the errors if they are needed later
const errors = validate.errors; // โ
// Use the draft export for the newer schema
import Ajv2020 from "ajv/dist/2020"; // โ
โ Don’t Do This:
// Use the shorthand in the hot path
ajv.validate(schema, data); // the compile check per call // โ
// Assume the errors persist
validate(data1); validate(data2); console.log(validate.errors); // the data2 errors // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| The validation is slow | The shorthand is used in the loop | Use the compile and reuse the function |
| The errors are from the wrong call | The validate.errors is overwritten | Copy the errors before the next call |
| The 2020-12 keyword is not recognized | The default export is used | Use the ajv/dist/2020 export |
| The TypeScript type guard does not narrow | The strictNullChecks is false | Enable the option |
Real-World Examples
1. The basic compile
const validate = ajv.compile(schema);
2. The validate
const valid = validate(data);
3. The errors
if (!valid) console.log(validate.errors);
4. The allErrors
const ajv = new Ajv({ allErrors: true });
5. The draft export
import Ajv2020 from "ajv/dist/2020";
6. The TypeScript annotation
const schema: JSONSchemaType<MyData> = { ... };
7. The type guard
if (validate(data)) { data.foo; }
8. The DefinedError
validate.errors as DefinedError[]
9. The addSchema
ajv.addSchema(addressSchema);
10. The custom format
ajv.addFormat("my-format", /^[A-Z]+$/);
Visual
The Compilation Flow
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ THE AJV COMPILATION โ
โ โ
โ The schema object โ
โ โ โ
โ โผ โ
โ โโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ ajv.compile(schema) โ The code generation โ
โ โโโโโโโโโโโโฌโโโโโโโโโโโ โ
โ โ โ
โ โผ โ
โ โโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ The validate โ The compiled function โ
โ โ function โ โ
โ โโโโโโโโโโโโฌโโโโโโโโโโโ โ
โ โ โ
โ โผ โ
โ โโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ validate(data) โ The fast validation โ
โ โโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The Draft Selection
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ THE DRAFT IMPORT โ
โ โ
โ The schema draft โ
โ โ โ
โ โผ โ
โ โโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ draft-07 โ "ajv" โ The default export โ
โ โ 2019-09 โ "ajv/2019"โ โ
โ โ 2020-12 โ "ajv/2020"โ โ
โ โ JTD โ "ajv/dist/jtd"โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ
โ The import is the draft choice. โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The TypeScript Type Guard
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ THE TYPE GUARD โ
โ โ
โ const validate = ajv.compile(schema); โ
โ โ โ
โ โผ โ
โ โโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ validate(data) โ The boolean โ
โ โโโโโโโโโโโโฌโโโโโโโโโโโ โ
โ โ โ
โ โโโโโโโโดโโโโโโโ โ
โ โผ โผ โ
โ โโโโโโโโโโ โโโโโโโโโโ โ
โ โ true โ โ false โ โ
โ โ โ โ โ โ
โ โdata is โ โerrors โ โ
โ โMyData โ โ โ โ
โ โโโโโโโโโโ โโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| The compilation | ajv.compile(schema) returns the validate function |
| The validation | validate(data) returns the boolean |
| The errors | validate.errors holds the failure details, overwritten per call |
| The draft default | draft-07 with the main ajv export |
| The draft 2020-12 | ajv/dist/2020 export |
| The TypeScript | JSONSchemaType<T> and the type guard |
| The error type | DefinedError for the type-safe handling |
Key takeaways:
- Ajv compiles the schema into a JavaScript function. The
ajv.compile(schema)returns the validate function, and the function is the fast path. The compilation is cached, and the same schema object returns the same function . - The
validate.errorsis overwritten on every call. The errors array is the failure details for the most recent validation, and it must be copied if it is needed later . TheallErrors: trueoption is the mechanism that collects every failure instead of the first. - The draft support is the import choice. The default
ajvexport is draft-07, theajv/dist/2019is 2019-09, and theajv/dist/2020is 2020-12. The separate export is the mechanism that keeps the draft-07 users from the bundle and the generated-code cost of the newer features . - The TypeScript integration is the type guard. The
JSONSchemaType<T>annotation makes the schema type-checked, and thevalidate(data)narrows the data type toTafter the successful validation . TheDefinedErroris the type-safe error handling. - The shorthand
ajv.validateis the convenience, not the performance path. The shorthand compiles the schema on the first call and re-checks the schema on every call. Thecompileis the explicit and the faster path for the hot validation .
Remember: Ajv is the JSON Schema compiler. The ajv.compile(schema) is the compilation, the validate(data) is the fast validation, and the validate.errors is the failure details. The draft support is the import choice, and the TypeScript integration is the type guard. The compilation is the once-per-schema cost, and the validation is the fast path. The errors are overwritten, and the copy is the mechanism that keeps them.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!