Use JSON schema to automatically validate and type requests

This package provides validation features based on json-schema.

This can be used to validate incoming JSON bodies, but can alternatively also be used to validate any data from ctx.request.body, this means it will work with form data just fine too.

In addition it will also create a new route /schemas, which is a collection where API clients can find all JSON schemas, so they may be re-used by clients.

The package uses ajv under the hood.


npm install @curveball/validator

Getting started

To get started, write a JSON schema to validate input. For example:

  "$schema": "",
  "$id": "",
  "title": "Article",
  "type": "object",
  "requiredProperties": ["title", "body"],
  "additionalProperties": false,

  "properties": {
    "title": { "type": "string" },
    "body": { "type": "string" }


For best results, we recommend using a full URI in $id. The domain should be your production API domain.

This allows the validator middleware to actually serve the schemas hosted on /schema/[schemaname.json], making things auto-documented.

After you created a schema file, and placed them in a directory, add the middleware:

import { Application } from '@curveball/kernel';
import validator from '@curveball/validator';

const app = new Application();
  // Provide path to your schema directory
  __dirname + '/schemas/'

  route('/article').post(ctx => {

    // Will throw an error if validation failed


Types for request body.

You might automatically convert your JSON Schema files to typescript types with tools such as json-schema-to-typescript.

If true, you can specify the type of the request body while validating:

  route('/article').post(ctx => {

    // ctx.request.body is now typed Article


By default ctx.request.body is typed unknown, but calling Validator with a Type pararameter will ‘assert it’ as that type if validation is successful.

Direct access to AJV

This middleware also exposes a ctx.ajv property. This property lets you directly use ajv.

This AJV instance has all the json schemas pre-compiled.