JSON Schema Boundary Validation
Validate untrusted request bodies with JSON Schema at the API boundary, reuse the schema for client forms, and evolve it with compatibility checks.
On this page
Introduction
This guide covers JSON Schema validation at the API boundary, a recurring concern in the form-validation scenario. A request body is untrusted until a schema says otherwise, and the cheapest place to enforce that is the boundary, before the payload reaches business logic. JSON Schema is a standard, so the same schema can drive server validation, client form generation, and documentation from one source.
Define the schema
State each field type, required keys, and constraints like minLength or maximum so the schema is the single source of truth for what the API accepts.
The trade-off worth naming is that state each field type, required keys, and constraints like minlength or maximum so the schema is the single source of truth for what the api accepts adds a measurable step to the hot path, so measure it before assuming it is free. A reasonable approach is to validate once at the edge, fail closed with a structured error, and log the rejection reason so a spike in bad input is visible on a dashboard rather than silent. Pair the implementation with a test that asserts a valid payload passes and at least one representative violation is rejected with the expected message; this is the cheapest way to keep the guarantee honest as the schema evolves.
{
"type": "object",
"properties": {
"email": { "type": "string", "format": "email" },
"age": { "type": "integer", "minimum": 0 }
},
"required": ["email"],
"additionalProperties": false
}
Compile once
Build the validator at module load and reuse it, because compiling a schema to a function is the costly step and doing it per request adds avoidable latency.
The trade-off worth naming is that build the validator at module load and reuse it, because compiling a schema to a function is the costly step and doing it per request adds avoidable latency adds a measurable step to the hot path, so measure it before assuming it is free. A reasonable approach is to validate once at the edge, fail closed with a structured error, and log the rejection reason so a spike in bad input is visible on a dashboard rather than silent. Pair the implementation with a test that asserts a valid payload passes and at least one representative violation is rejected with the expected message; this is the cheapest way to keep the guarantee honest as the schema evolves.
import Ajv from 'ajv';
const ajv = new Ajv({ allErrors: true });
const validate = ajv.compile(schema);
export function check(body) {
const ok = validate(body);
return ok ? { ok: true } : { ok: false, errors: validate.errors };
}
Reject with structure
Return a 400 with a JSON body listing each offending path and message so the client can map errors to fields instead of guessing from a string.
The trade-off worth naming is that return a 400 with a json body listing each offending path and message so the client can map errors to fields instead of guessing from a string adds a measurable step to the hot path, so measure it before assuming it is free. A reasonable approach is to validate once at the edge, fail closed with a structured error, and log the rejection reason so a spike in bad input is visible on a dashboard rather than silent. Pair the implementation with a test that asserts a valid payload passes and at least one representative violation is rejected with the expected message; this is the cheapest way to keep the guarantee honest as the schema evolves.
Share with the client
Publish the schema so the client can generate a form and validate before submit, which cuts round trips and gives the user instant feedback from the same rules.
The trade-off worth naming is that publish the schema so the client can generate a form and validate before submit, which cuts round trips and gives the user instant feedback from the same rules adds a measurable step to the hot path, so measure it before assuming it is free. A reasonable approach is to validate once at the edge, fail closed with a structured error, and log the rejection reason so a spike in bad input is visible on a dashboard rather than silent. Pair the implementation with a test that asserts a valid payload passes and at least one representative violation is rejected with the expected message; this is the cheapest way to keep the guarantee honest as the schema evolves.
Evolve safely
Adding an optional field is safe; removing one or tightening a type is breaking, so run a compatibility check in CI and version the schema when it fails.
The trade-off worth naming is that adding an optional field is safe; removing one or tightening a type is breaking, so run a compatibility check in ci and version the schema when it fails adds a measurable step to the hot path, so measure it before assuming it is free. A reasonable approach is to validate once at the edge, fail closed with a structured error, and log the rejection reason so a spike in bad input is visible on a dashboard rather than silent. Pair the implementation with a test that asserts a valid payload passes and at least one representative violation is rejected with the expected message; this is the cheapest way to keep the guarantee honest as the schema evolves.
function compatible(old, neu) {
const problems = [];
for (const k of Object.keys(old.properties)) {
if (!(k in neu.properties)) problems.push('removed ' + k);
}
return problems;
}
Test the boundary
Assert a valid body passes, a missing required field fails with its path, and an extra field is rejected when additionalProperties is false, so the contract is enforced.
The trade-off worth naming is that assert a valid body passes, a missing required field fails with its path, and an extra field is rejected when additionalproperties is false, so the contract is enforced adds a measurable step to the hot path, so measure it before assuming it is free. A reasonable approach is to validate once at the edge, fail closed with a structured error, and log the rejection reason so a spike in bad input is visible on a dashboard rather than silent. Pair the implementation with a test that asserts a valid payload passes and at least one representative violation is rejected with the expected message; this is the cheapest way to keep the guarantee honest as the schema evolves.
Sources
Sources: JSON Schema spec, Ajv validator.
FAQ
- Should I compile the schema on every request?
- No; compile once at startup and reuse the validator function, since compilation is the expensive step and running it per request wastes CPU and adds latency.
- How do I keep the schema from breaking clients?
- Treat removing a field or tightening a type as breaking, run a compatibility check in CI against the previous schema, and bump the major version when the check fails.
Report a problem with this articleOpens a pre-filled issue on GitHub.