All Projects → simonplend → express-json-validator-middleware

simonplend / express-json-validator-middleware

Licence: MIT license
Express middleware for validating requests against JSON schema

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to express-json-validator-middleware

Node Iframe Replacement
An alternative to sticking that lovely web app you just built into an <iframe> on a corp website
Stars: ✭ 37 (-75%)
Mutual labels:  express-middleware, expressjs
Express Openapi Validator
🦋 Auto-validates api requests, responses, and securities using ExpressJS and an OpenAPI 3.x specification
Stars: ✭ 436 (+194.59%)
Mutual labels:  express-middleware, expressjs
express-expeditious
flexible caching middleware for express endpoints
Stars: ✭ 42 (-71.62%)
Mutual labels:  express-middleware, expressjs
openui5-validator
A library to validate OpenUI5 fields
Stars: ✭ 17 (-88.51%)
Mutual labels:  json-schema, ajv
Limitrr
Light NodeJS rate limiting and response delaying using Redis - including Express middleware.
Stars: ✭ 203 (+37.16%)
Mutual labels:  express-middleware, expressjs
Mernapp youtube
Build a MERN Stack App from scratch, and deploy it to Heroku
Stars: ✭ 51 (-65.54%)
Mutual labels:  express-middleware, expressjs
Webpack Hot Server Middleware
🔥 Hot reload webpack bundles on the server
Stars: ✭ 319 (+115.54%)
Mutual labels:  express-middleware, expressjs
Webauthn
W3C Web Authentication API Relying Party for Node.js and Express
Stars: ✭ 61 (-58.78%)
Mutual labels:  express-middleware, expressjs
Express Gateway
A microservices API Gateway built on top of Express.js
Stars: ✭ 2,583 (+1645.27%)
Mutual labels:  express-middleware, expressjs
Ajv
The fastest JSON schema Validator. Supports JSON Schema draft-04/06/07/2019-09/2020-12 and JSON Type Definition (RFC8927)
Stars: ✭ 10,340 (+6886.49%)
Mutual labels:  json-schema, ajv
jsonresume-theme-caffeine
Caffeine theme for the JSON Resume project
Stars: ✭ 78 (-47.3%)
Mutual labels:  json-schema
chronos-pipeline
A data pipeline for processing event data
Stars: ✭ 20 (-86.49%)
Mutual labels:  expressjs
Rockets
REST and websockets C++ library
Stars: ✭ 39 (-73.65%)
Mutual labels:  json-schema
node-express-mongodb-reactjs-graphql
Node, Express, React.js, Graphql and MongoDB CRUD Web Application
Stars: ✭ 36 (-75.68%)
Mutual labels:  expressjs
express-file-upload
Node.js Express Upload/Download File Rest APIs example with Multer
Stars: ✭ 64 (-56.76%)
Mutual labels:  expressjs
react-app-simple-chat-app
A Simple Chat Application using MERN stack (MongoDB, Express JS, React JS, Node JS) and Socket.io for real time chatting
Stars: ✭ 41 (-72.3%)
Mutual labels:  expressjs
in-memory-db
Simple In-Memory DB Service for NestJS projects
Stars: ✭ 55 (-62.84%)
Mutual labels:  expressjs
json-schema
Clojure library JSON Schema validation and generation - Draft-07 compatible
Stars: ✭ 52 (-64.86%)
Mutual labels:  json-schema
dword
Web editor based on CodeMirror
Stars: ✭ 37 (-75%)
Mutual labels:  expressjs
oors
Modular node.js framework for makers.
Stars: ✭ 25 (-83.11%)
Mutual labels:  expressjs

Express JSON Validator Middleware

Express middleware for validating requests against JSON schemas with Ajv.

npm version npm monthly downloads npm license Build status codecov

Why validate with JSON schemas?

  • Expressive — JSON schemas are an expressive way to describe data structures.
  • Standard — JSON schemas are portable. There are validator implementations in many languages.
  • Separate validation — Avoid the need to handle request validation in your route handlers.
  • Error messaging — Ajv provides rich and descriptive error objects.
  • Documentation — Schemas can help document your application.

Requirements

Installation

npm install express-json-validator-middleware

If you're upgrading from v2 to v3, make sure you read the migration notes.

Getting started

import { Validator } from "express-json-validator-middleware";

/**
 * Define a JSON schema.
 */
const addressSchema = {
  type: "object",
  required: ["street"],
  properties: {
    street: {
      type: "string",
    }
  },
};

/**
 * Initialize a `Validator` instance, optionally passing in
 * an Ajv options object.
 *
 * @see https://github.com/ajv-validator/ajv/tree/v6#options
 */
 const { validate } = new Validator();

/**
 * The `validate` method accepts an object which maps request
 * properties to the JSON schema you want them to be validated
 * against e.g.
 *
 * { requestPropertyToValidate: jsonSchemaObject }
 *
 * Validate `request.body` against `addressSchema`.
 */
app.post("/address", validate({ body: addressSchema }), (request, response) => {
  /**
   * Route handler logic to run when `request.body` has been validated.
   */
  response.send({});
});

Coming from express-jsonschema? Read the migration notes.

Schemas in TypeScript

If you're writing JSON schemas in TypeScript, you'll need to use the AllowedSchema type e.g.

import { AllowedSchema } from "express-json-validator-middleware";

const addressSchema: AllowedSchema  = {
  type: "object",
  required: ["street"],
  properties: {
    street: {
      type: "string",
    }
  },
};

This is required so TypeScript doesn't attempt to widen the types of values in the schema object. If you omit this type, TypeScript will raise an error.

See issues #39 and #102 for more background.

Error handling

On encountering invalid data, the validator will call next() with a ValidationError object. It is recommended to setup a general error handler for your app where you handle ValidationError errors.

Example - error thrown for the body request property:

ValidationError {
    name: "JsonSchemaValidationError",
    validationErrors: {
        body: [AjvError]
    }
}

More information on Ajv errors.

Example Express application

import express from "express";

import { Validator, ValidationError } from "express-json-validator-middleware";

const app = express();

app.use(express.json());

const addressSchema = {
  type: "object",
  required: ["number", "street", "type"],
  properties: {
    number: {
      type: "number",
    },
    street: {
      type: "string",
    },
    type: {
      type: "string",
      enum: ["Street", "Avenue", "Boulevard"],
    },
  },
};

const { validate } = new Validator();

/**
 * Validate `request.body` against `addressSchema`.
 */
app.post("/address", validate({ body: addressSchema }), (request, response) => {
  /**
   * Route handler logic to run when `request.body` has been validated.
   */
  response.send({});
});

/**
 * Error handler middleware for validation errors.
 */
app.use((error, request, response, next) => {
  // Check the error is a validation error
  if (error instanceof ValidationError) {
    // Handle the error
    response.status(400).send(error.validationErrors);
    next();
  } else {
    // Pass error on if not a validation error
    next(error);
  }
});

app.listen(3000);

Validating multiple request properties

Sometimes your route may depend on the body and query both having a specific format. In this example we use body and query but you can choose to validate any request properties you like. This example builds on the Example Express application.

const tokenSchema = {
  type: "object",
  required: ["token"],
  properties: {
    token: {
      type: "string",
      minLength: 36,
      maxLength: 36
    },
  },
};

app.post(
  "/address",
  validate({ body: addressSchema, query: tokenSchema }),
  (request, response) => {
    /**
     * Route handler logic to run when `request.body` and
     * `request.query` have both been validated.
     */
    response.send({});
  }
);

A valid request must now include a token URL query. Example valid URL: /street/?uuid=af3996d0-0e8b-4165-ae97-fdc0823be417

Using dynamic schema

Instead of passing in a schema object you can also pass in a function that will return a schema. It is useful if you need to generate or alter the schema based on the request object.

Example: Loading schema from a database (this example builds on the Example Express application):

function getSchemaFromDb() {
  /**
   * In a real application this would be making a database query.
   */
  return Promise.resolve(addressSchema);
}

/**
 * Middleware to set schema on the `request` object.
 */
async function loadSchema(request, response, next) {
  try {
    request.schema = await getSchemaFromDb();
    next();
  } catch (error) {
    next(error);
  }
}

/**
 * Get schema set by the `loadSchema` middleware.
 */
function getSchema(request) {
  return request.schema;
}

app.post(
  "/address",
  loadSchema,
  validate({ body: getSchema }),
  (request, response) => {
    /**
     * Route handler logic to run when `request.body` has been validated.
     */
    response.send({});
  }
);

Ajv instance

The Ajv instance can be accessed via validator.ajv.

import { Validator, ValidationError } from "express-json-validator-middleware";

const validator = new Validator();

// Ajv instance
validator.ajv;

Ajv must be configured before you call Validator.validate() to add middleware (e.g. if you need to define custom keywords.

Upgrading from v2 to v3

v2.x releases of this library use Ajv v6. v3.x of this library uses Ajv v8.

Notable changes between Ajv v6 and v8:

  • All formats have been moved to ajv-formats. If you're using formats in your schemas, you must install this package to continue using them.
  • The structure of validation errors has changed.
  • Support has been dropped for JSON Schema draft-04.

For full details, read the Ajv migration guide: Changes from Ajv v6.12.6 to v8.0.0.

If you have any Ajv plugins as dependencies, update them to their newest versions. Older versions of Ajv plugins are less likely to be compatible with Ajv v8.

Tests

Tests are written using node-tap.

npm install

npm test

More documentation on JSON Schema

Credits

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].