{"id":19924141,"url":"https://github.com/vacekj/express-json-validator-middleware","last_synced_at":"2025-04-30T09:12:37.004Z","repository":{"id":39963286,"uuid":"86083408","full_name":"vacekj/express-json-validator-middleware","owner":"vacekj","description":"Express middleware for validating requests against JSON schema","archived":false,"fork":false,"pushed_at":"2024-08-07T17:00:28.000Z","size":1998,"stargazers_count":158,"open_issues_count":5,"forks_count":26,"subscribers_count":6,"default_branch":"main","last_synced_at":"2025-04-22T13:06:17.939Z","etag":null,"topics":["ajv","express","express-middleware","expressjs","json","json-schema","json-schemas"],"latest_commit_sha":null,"homepage":"https://npm.im/express-json-validator-middleware","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/vacekj.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":null},"created_at":"2017-03-24T15:33:00.000Z","updated_at":"2025-04-21T17:03:21.000Z","dependencies_parsed_at":"2024-06-18T13:46:13.972Z","dependency_job_id":"b693e701-a81d-403e-b027-dad94bd56d3f","html_url":"https://github.com/vacekj/express-json-validator-middleware","commit_stats":{"total_commits":156,"total_committers":15,"mean_commits":10.4,"dds":0.3653846153846154,"last_synced_commit":"64ddb75a69c78d60a30d91aaee9bfef671e5b6f6"},"previous_names":[],"tags_count":12,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/vacekj%2Fexpress-json-validator-middleware","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/vacekj%2Fexpress-json-validator-middleware/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/vacekj%2Fexpress-json-validator-middleware/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/vacekj%2Fexpress-json-validator-middleware/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/vacekj","download_url":"https://codeload.github.com/vacekj/express-json-validator-middleware/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":251674580,"owners_count":21625645,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ajv","express","express-middleware","expressjs","json","json-schema","json-schemas"],"created_at":"2024-11-12T22:16:30.568Z","updated_at":"2025-04-30T09:12:36.981Z","avatar_url":"https://github.com/vacekj.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Express JSON Validator Middleware\n\n\u003e [Express](https://github.com/expressjs/express/) middleware for validating\nrequests against JSON schemas with Ajv.\n\n[![npm version](https://img.shields.io/npm/v/express-json-validator-middleware.svg)](https://www.npmjs.com/package/express-json-validator-middleware)\n[![npm monthly downloads](https://img.shields.io/npm/dm/express-json-validator-middleware.svg)](https://www.npmjs.com/package/express-json-validator-middleware)\n[![npm license](https://img.shields.io/npm/l/express-json-validator-middleware.svg)](https://www.npmjs.com/package/express-json-validator-middleware)\n[![Build status](https://github.com/vacekj/express-json-validator-middleware/workflows/Node.js%20CI/badge.svg)](https://github.com/vacekj/express-json-validator-middleware/actions?query=workflow%3A%22Node.js+CI%22)\n[![codecov](https://codecov.io/gh/vacekj/express-json-validator-middleware/branch/master/graph/badge.svg)](https://codecov.io/gh/vacekj/express-json-validator-middleware)\n\n## Why validate with JSON schemas?\n\n- **Expressive** — JSON schemas are an expressive way to describe data structures.\n- **Standard** — JSON schemas are portable. There are validator implementations in many languages.\n- **Separate validation** — Avoid the need to handle request validation in your route handlers.\n- **Error messaging** — Ajv provides rich and descriptive error objects.\n- **Documentation** — Schemas can help document your application.\n\n## Requirements\n\n- [Node.js](https://nodejs.org/en/download/) \u003e= v14\n\n## Installation\n\n```sh\nnpm install express-json-validator-middleware\n```\n\nIf you're upgrading from v2 to v3, make sure you read the [migration notes](#upgrading-from-v2-to-v3).\n\n## Getting started\n\n```javascript\nimport { Validator } from \"express-json-validator-middleware\";\n\n/**\n * Define a JSON schema.\n */\nconst addressSchema = {\n  type: \"object\",\n  required: [\"street\"],\n  properties: {\n    street: {\n      type: \"string\",\n    }\n  },\n};\n\n/**\n * Initialize a `Validator` instance, optionally passing in\n * an Ajv options object.\n *\n * @see https://github.com/ajv-validator/ajv/tree/v6#options\n */\n const { validate } = new Validator();\n\n/**\n * The `validate` method accepts an object which maps request\n * properties to the JSON schema you want them to be validated\n * against e.g.\n *\n * { requestPropertyToValidate: jsonSchemaObject }\n *\n * Validate `request.body` against `addressSchema`.\n */\napp.post(\"/address\", validate({ body: addressSchema }), (request, response) =\u003e {\n  /**\n   * Route handler logic to run when `request.body` has been validated.\n   */\n  response.send({});\n});\n```\n\nComing from `express-jsonschema`? Read the [migration notes](docs/migrating-from-express-jsonschema.md).\n\n### Schemas in TypeScript\n\nIf you're writing JSON schemas in TypeScript, you'll need to use the\n`AllowedSchema` type and this can be combined with [ajv's recommended `JSONSchemaType` type](https://ajv.js.org/guide/typescript.html) e.g.\n\n```typescript\nimport { JSONSchemaType } from \"ajv\";\nimport { AllowedSchema } from \"express-json-validator-middleware\";\n\ntype Address = { street: string; };\nconst addressSchema: AllowedSchema \u0026 JSONSchemaType\u003cAddress\u003e = {\n  type: \"object\",\n  required: [\"street\"],\n  properties: {\n    street: {\n      type: \"string\",\n    }\n  },\n};\n```\n\nThis is required so TypeScript doesn't attempt to widen the types of values\nin the schema object. If you omit this type, TypeScript will raise an error.\n\nSee issues [#39](https://github.com/simonplend/express-json-validator-middleware/issues/39)\nand [#102](https://github.com/simonplend/express-json-validator-middleware/issues/102)\nfor more background.\n\n## Error handling\n\nOn encountering invalid data, the validator will call `next()` with a\n`ValidationError` object. It is recommended to setup a general error handler\nfor your app where you handle `ValidationError` errors.\n\nExample - error thrown for the `body` request property:\n\n```javascript\nValidationError {\n    name: \"JsonSchemaValidationError\",\n    validationErrors: {\n        body: [AjvError]\n    }\n}\n```\n\nMore information on [Ajv errors](https://github.com/ajv-validator/ajv/tree/v6#validation-errors).\n\n## Example Express application\n\n```javascript\nimport express from \"express\";\n\nimport { Validator, ValidationError } from \"express-json-validator-middleware\";\n\nconst app = express();\n\napp.use(express.json());\n\nconst addressSchema = {\n  type: \"object\",\n  required: [\"number\", \"street\", \"type\"],\n  properties: {\n    number: {\n      type: \"number\",\n    },\n    street: {\n      type: \"string\",\n    },\n    type: {\n      type: \"string\",\n      enum: [\"Street\", \"Avenue\", \"Boulevard\"],\n    },\n  },\n};\n\nconst { validate } = new Validator();\n\n/**\n * Validate `request.body` against `addressSchema`.\n */\napp.post(\"/address\", validate({ body: addressSchema }), (request, response) =\u003e {\n  /**\n   * Route handler logic to run when `request.body` has been validated.\n   */\n  response.send({});\n});\n\n/**\n * Error handler middleware for validation errors.\n */\napp.use((error, request, response, next) =\u003e {\n  // Check the error is a validation error\n  if (error instanceof ValidationError) {\n    // Handle the error\n    response.status(400).send(error.validationErrors);\n    next();\n  } else {\n    // Pass error on if not a validation error\n    next(error);\n  }\n});\n\napp.listen(3000);\n```\n\n## Validating multiple request properties\n\nSometimes your route may depend on the `body` and `query` both having a specific\nformat. In this example we use `body` and `query` but you can choose to validate\nany `request` properties you like. This example builds on the\n[Example Express application](#example-express-application).\n\n```javascript\nconst tokenSchema = {\n  type: \"object\",\n  required: [\"token\"],\n  properties: {\n    token: {\n      type: \"string\",\n      minLength: 36,\n      maxLength: 36\n    },\n  },\n};\n\napp.post(\n  \"/address\",\n  validate({ body: addressSchema, query: tokenSchema }),\n  (request, response) =\u003e {\n    /**\n     * Route handler logic to run when `request.body` and\n     * `request.query` have both been validated.\n     */\n    response.send({});\n  }\n);\n```\n\nA valid request must now include a token URL query. Example valid URL:\n`/street/?token=af3996d0-0e8b-4165-ae97-fdc0823be417`\n\nThe same kind of validation can also be performed on path parameters. Repurposing our earlier example,\nwe could expect the client to send us the UUID.\n\n```javascript\nconst pathSchema = {\n  type: \"object\",\n  required: [\"uuid\"],\n  properties: {\n    uuid: {\n      type: \"string\",\n      minLength: 36,\n      maxLength: 36\n    },\n  },\n};\n\napp.get(\n  \"/address/:uuid\",\n  validate({ body: addressSchema, params: pathSchema }),\n  (request, response) =\u003e {\n    /**\n     * Route handler logic to run when `request.body` and\n     * `request.params` have both been validated.\n     */\n    response.send({});\n  }\n);\n```\n\n## Using dynamic schema\n\nInstead of passing in a schema object you can also pass in a function that will\nreturn a schema. It is useful if you need to generate or alter the schema based\non the request object.\n\nExample: Loading schema from a database (this example builds on the\n[Example Express application](#example-express-application)):\n\n```javascript\nfunction getSchemaFromDb() {\n  /**\n   * In a real application this would be making a database query.\n   */\n  return Promise.resolve(addressSchema);\n}\n\n/**\n * Middleware to set schema on the `request` object.\n */\nasync function loadSchema(request, response, next) {\n  try {\n    request.schema = await getSchemaFromDb();\n    next();\n  } catch (error) {\n    next(error);\n  }\n}\n\n/**\n * Get schema set by the `loadSchema` middleware.\n */\nfunction getSchema(request) {\n  return request.schema;\n}\n\napp.post(\n  \"/address\",\n  loadSchema,\n  validate({ body: getSchema }),\n  (request, response) =\u003e {\n    /**\n     * Route handler logic to run when `request.body` has been validated.\n     */\n    response.send({});\n  }\n);\n```\n\n## Ajv instance\n\nThe Ajv instance can be accessed via `validator.ajv`.\n\n```javascript\nimport { Validator, ValidationError } from \"express-json-validator-middleware\";\n\nconst validator = new Validator();\n\n// Ajv instance\nvalidator.ajv;\n```\n\nAjv must be configured *before* you call `Validator.validate()` to add middleware\n(e.g. if you need to define [custom keywords](https://ajv.js.org/custom.html).\n\n## Upgrading from v2 to v3\n\nv2.x releases of this library use [Ajv v6](https://www.npmjs.com/package/ajv/v/6.6.2).\nv3.x of this library uses [Ajv v8](https://www.npmjs.com/package/ajv/v/8.11.0).\n\nNotable changes between Ajv v6 and v8:\n\n- All formats have been moved to [ajv-formats](https://www.npmjs.com/package/ajv-formats).\nIf you're using formats in your schemas, you must install this package to continue\nusing them.\n- The structure of validation errors has changed.\n- Support has been dropped for JSON Schema draft-04.\n\nFor full details, read the Ajv migration guide: [Changes from Ajv v6.12.6 to v8.0.0](https://ajv.js.org/v6-to-v8-migration.html).\n\nIf you have any Ajv plugins as dependencies, update them to their newest versions.\nOlder versions of Ajv plugins are less likely to be compatible with Ajv v8.\n\n## Tests\n\nTests are written using [node-tap](https://www.npmjs.com/package/tap).\n\n```\nnpm install\n\nnpm test\n```\n\n## More documentation on JSON Schema\n\n- [Understanding JSON Schema](https://json-schema.org/understanding-json-schema/index.html)\n\n## Credits\n\n- Maintained by [@simonplend](https://github.com/simonplend/)\n- Created and previously maintained by [@vacekj](https://github.com/vacekj/)\n- Thank you to all of this project's [contributors](https://github.com/vacekj/express-json-validator-middleware/graphs/contributors)\n- Based on the [express-json-schema](https://github.com/trainiac/express-jsonschema) library by [@trainiac](https://github.com/trainiac)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fvacekj%2Fexpress-json-validator-middleware","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fvacekj%2Fexpress-json-validator-middleware","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fvacekj%2Fexpress-json-validator-middleware/lists"}