Validate JSON with AJV: A Quick Guide to Draft‑07 Schemas in Node.js
Validate JSON payloads in Node.js with AJV and Draft‑07 schemas. See a concise code example, learn about limits, and avoid common pitfalls for robust data validation.
03 Jul 2025, 00:14 UTC

Why Validate JSON?
When a Node.js service receives JSON payloads, you want to guarantee that the data matches an expected shape before you process it. JSON Schema, a machine‑readable description of JSON structure, lets you enforce types, required fields, value ranges, and more. The AJV library compiles a schema into a fast JavaScript function that performs the validation at runtime.
How AJV Uses a Draft‑07 Schema
AJV parses a JSON Schema document that follows the Draft‑07 specification. It then creates a validator function that walks the input object, checking each property against the schema rules. The process is:
- Parse the schema file.
- Compile the schema into a JavaScript function.
- Run the compiled function against your data.
- Receive a boolean result and an array of error objects if validation fails.
Because the validator is pre‑compiled, validation is usually faster than a manual check and is safe from injection attacks that could arise from evaluating arbitrary code.
Concrete Example
Below is a minimal Node.js script that:
- Defines a Draft‑07 schema for a user object.
- Compiles the schema with AJV.
- Validates a sample data object.
- Logs the validation result and any errors.
// Install AJV first: npm install ajv
const Ajv = require('ajv');
// Create an AJV instance – defaults to Draft‑07
const ajv = new Ajv();
// Draft‑07 schema for a user
const schema = {
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"name": { "type": "string" },
"age": { "type": "integer", "minimum": 18 },
"tags": {
"type": "array",
"items": { "type": "string" }
}
},
"required": ["name", "age"],
"additionalProperties": false
};
// Compile the schema into a validator function
const validate = ajv.compile(schema);
// Sample data to validate
const data = {
"name": "Alice",
"age": 25,
"tags": ["admin", "editor"]
};
const valid = validate(data);
console.log('Is data valid?', valid); // Expected: true
if (!valid) {
console.log('Errors:', validate.errors);
}
Run the script with node validate.js. The console should display:
Is data valid? true
Typical Limitations
| Limitation | Explanation |
|---|---|
| Limited Cross‑Field Logic | Draft‑07 supports simple dependencies but cannot express complex relationships (e.g., “if field A is X, then field B must be Y”). |
| External Uniqueness | Schema cannot enforce uniqueness against an external data source (e.g., “email must be unique in the database”). |
| Recursion Depth | AJV’s default recursion limit is 100. Deeply nested schemas may trigger a stack overflow. |
| Runtime Constraints | It validates structure only; it does not check runtime conditions like authentication or business rules. |
Common Pitfalls and How to Avoid Them
- Wrong Draft Version: Using a Draft‑2019‑09 keyword with a Draft‑07 validator will silently ignore the keyword. Ensure the AJV instance matches the schema draft.
- Missing
required: Without specifying required properties, AJV will accept missing fields as long as they are not present. - Misunderstanding
additionalProperties: Setting it tofalseblocks unknown keys only at the top level unless you apply the same rule inside nested objects. - Unresolved
$ref: Splitting schemas across files requires a proper$idand a resolver; otherwise AJV throws a reference error. - Circular References: Circular
$refchains need explicit$iddeclarations and thestrictoption set tofalseor a custom resolver to avoid crashes.
Practical Validation Checklist
- Write the schema in Draft‑07 syntax and save it as
schema.json. - Run
ajv compile -s schema.json -d data.jsonto validate a file from the command line. - In code, compile the schema once at startup and reuse the validator function for each request.
- When validation fails, inspect
validate.errorsto provide meaningful feedback to API consumers. - Periodically test the schema with sample data using an online validator (e.g., https://jsonschema.net) to catch accidental drift.
Conclusion
AJV and Draft‑07 JSON Schema give you a declarative, fast way to enforce data contracts in Node.js. By understanding the limits and avoiding the common mistakes above, you can integrate reliable validation into your API pipeline without adding runtime complexity.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.