Checking that a string is valid JSON only tells you it parses. Real code also needs to know the data has the right shape: required fields present, numbers in range, no unexpected keys. JSON Schema is the standard way to describe that shape, and Ajv is the most widely used JavaScript validator for it.
Install
npm install ajv ajv-formats
A first schema
import Ajv2020 from "ajv/dist/2020.js";
import addFormats from "ajv-formats";
const ajv = new Ajv2020({ allErrors: true });
addFormats(ajv);
const userSchema = {
$schema: "https://json-schema.org/draft/2020-12/schema",
type: "object",
properties: {
id: { type: "integer", minimum: 1 },
email: { type: "string", format: "email" },
role: { enum: ["admin", "editor", "viewer"] },
tags: { type: "array", items: { type: "string" }, uniqueItems: true },
},
required: ["id", "email"],
additionalProperties: false,
};
const validate = ajv.compile(userSchema);
const data = { id: 0, email: "not-an-email", role: "owner", extra: true };
if (!validate(data)) {
console.log(validate.errors.map((e) => `${e.instancePath || "/"} ${e.message}`));
}
Output:
[
'/ must NOT have additional properties',
'/id must be >= 1',
'/email must match format "email"',
'/role must be equal to one of the allowed values'
]
allErrors: true reports every problem rather than stopping at the first, which is what you want for form and API error messages. Import Ajv from "ajv" instead of "ajv/dist/2020.js" for draft-07 schemas.
Keywords you'll use most
| Keyword | Applies to | Example |
|---|---|---|
type |
any | "string", "integer", ["string", "null"] |
enum, const |
any | { "enum": ["a", "b"] } |
properties, required |
object | Field definitions and mandatory keys |
additionalProperties |
object | false rejects unknown keys |
minLength, maxLength, pattern |
string | { "pattern": "^[a-z0-9-]+$" } |
format |
string | email, uri, date-time, uuid, ipv4 |
minimum, maximum, multipleOf |
number | { "minimum": 0 } |
items, minItems, uniqueItems |
array | { "items": { "type": "string" } } |
oneOf, anyOf, allOf |
any | Alternatives and combinations |
$ref, $defs |
any | Reuse definitions |
Reusing definitions
{
"$defs": {
"address": {
"type": "object",
"properties": { "city": { "type": "string" }, "zip": { "type": "string" } },
"required": ["city"]
}
},
"type": "object",
"properties": {
"billing": { "$ref": "#/$defs/address" },
"shipping": { "$ref": "#/$defs/address" }
}
}
Nullable fields
{ "middleName": { "type": ["string", "null"] } }
Validate API input
In an Express handler, return the errors as a 400 response:
const validateUser = ajv.compile(userSchema);
app.post("/users", express.json(), (req, res) => {
if (!validateUser(req.body)) {
return res.status(400).json({
error: "Invalid request body",
details: validateUser.errors.map((e) => ({ path: e.instancePath, message: e.message })),
});
}
// req.body has the expected shape here
});
Fastify uses Ajv internally: pass the schema as schema: { body: userSchema } on the route and it validates for you.
Useful Ajv options
new Ajv2020({
allErrors: true, // report all errors
removeAdditional: "all",// strip unknown keys instead of failing
useDefaults: true, // fill in "default" values from the schema
coerceTypes: true, // "42" → 42, useful for query strings
});
removeAdditional, useDefaults and coerceTypes modify the data you pass in. That's often convenient for request handling, but surprising elsewhere, so enable them deliberately.
Pitfalls
Forgetting additionalProperties
Without additionalProperties: false, an object with a misspelled key (emial) passes, and the required field check is the only thing that catches it. Decide per object whether unknown keys should be rejected, ignored or stripped.
Mixing drafts
Keywords changed between drafts: definitions became $defs, and array tuple validation moved from items arrays to prefixItems. Ajv validates with the draft its class implements, so use Ajv2020 for 2020-12 schemas.
"integer" vs "number"
"type": "integer" rejects 1.5; "number" accepts it. JSON doesn't distinguish 1 from 1.0, and Ajv treats 1.0 as an integer.
Validating TypeScript types at runtime
TypeScript types disappear at runtime, so they can't check API responses. A schema can. Typing API responses in TypeScript covers keeping types and runtime validation in sync.
Where schemas help beyond validation
- Editor support: VS Code validates and autocompletes JSON and YAML files that reference a schema.
- Documentation: OpenAPI 3.1 describes request and response bodies with JSON Schema.
- Config files: validating YAML config against a schema catches the silent type problems described in YAML vs JSON.