{"id":18589625,"url":"https://github.com/jakefenley/koa-zod-router","last_synced_at":"2025-10-24T15:35:51.632Z","repository":{"id":65305343,"uuid":"587644419","full_name":"JakeFenley/koa-zod-router","owner":"JakeFenley","description":"Build typesafe routes for Koa with ease. Utilizes Typescript, Zod, and Koa-Router to provide an easy solution to I/O validation and type inference.","archived":false,"fork":false,"pushed_at":"2024-10-01T22:19:28.000Z","size":425,"stargazers_count":65,"open_issues_count":2,"forks_count":2,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-28T21:01:35.315Z","etag":null,"topics":["api","endpoint","http","koa","koa-router","middleware","nodejs","router","schema","schema-validation","server","typescript","validation","zod"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","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/JakeFenley.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-01-11T08:39:24.000Z","updated_at":"2025-03-19T04:18:45.000Z","dependencies_parsed_at":"2024-11-07T00:52:53.377Z","dependency_job_id":null,"html_url":"https://github.com/JakeFenley/koa-zod-router","commit_stats":{"total_commits":132,"total_committers":4,"mean_commits":33.0,"dds":0.2272727272727273,"last_synced_commit":"4c0e2aad8608421ec3cde75452c4371406b3667a"},"previous_names":[],"tags_count":16,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JakeFenley%2Fkoa-zod-router","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JakeFenley%2Fkoa-zod-router/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JakeFenley%2Fkoa-zod-router/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JakeFenley%2Fkoa-zod-router/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/JakeFenley","download_url":"https://codeload.github.com/JakeFenley/koa-zod-router/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247256093,"owners_count":20909240,"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":["api","endpoint","http","koa","koa-router","middleware","nodejs","router","schema","schema-validation","server","typescript","validation","zod"],"created_at":"2024-11-07T00:52:49.014Z","updated_at":"2025-10-24T15:35:46.608Z","avatar_url":"https://github.com/JakeFenley.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# ⚡ koa-zod-router ⚡\n\nInspired by koa-joi-router, this package aims to provide a similar feature-set while leveraging Zod and Typescript to create typesafe routes and middlewares with built in I/O validation.\n\n![npm release](https://img.shields.io/npm/v/koa-zod-router?label=latest)\n[![Coverage Status](https://coveralls.io/repos/github/JakeFenley/koa-zod-router/badge.svg?branch=main)](https://coveralls.io/github/JakeFenley/koa-zod-router?branch=main)\n![downloads](https://img.shields.io/npm/dm/koa-zod-router)\n\n[zod]: https://github.com/colinhacks/zod\n[coercion]: https://zod.dev/?id=coercion-for-primitives\n[koa-bodyparser]: https://github.com/koajs/bodyparser\n[formidable]: https://github.com/node-formidable/formidable\n[@koa/router]: https://github.com/koajs/router\n\n## 🔥 Features:\n\n- Input/output validation and typesafety using [zod][]\n- Body parsing using [koa-bodyparser][]\n- Multipart parsing using [formidable][]\n- Wraps [@koa/router][], providing the same API but with typesafety and validation.\n- Custom validation error handling support\n- RegExp path support\n- CJS and ESM support\n\n## 🚀 Install\n\n```sh\nnpm install koa-zod-router\n```\n\n## 🚦 Quickstart\n\n`index.ts:`\n\n```js\nimport Koa from 'koa';\nimport zodRouter from 'koa-zod-router';\nimport { z } from 'zod';\n\nconst app = new Koa();\n\nconst router = zodRouter();\n\nrouter.register({\n  name: 'example',\n  method: 'post',\n  path: '/post/:id',\n  handler: async (ctx, next) =\u003e {\n    const { foo } = ctx.request.body;\n    ctx.body = { hello: 'world' };\n\n    await next();\n  },\n  validate: {\n    params: z.object({ id: z.coerce.number() }),\n    body: z.object({ foo: z.number() }),\n    response: z.object({ hello: z.string() }),\n  },\n});\n\napp.use(router.routes());\n\napp.listen(3000, () =\u003e {\n  console.log('app listening on http://localhost:3000');\n});\n```\n\n### Importing/Exporting routes\n\nMost likely you'll want to seperate your routes into seperate files, and register them somewhere in your app's initialization phase. To do this you can use the helper function createRouteSpec and specify the route's properties.\n\n`get-user.ts:`\n\n```js\nimport { createRouteSpec } from 'koa-zod-router';\nimport { z } from 'zod';\n\nexport const getUserRoute = createRouteSpec({\n  method: 'get',\n  path: '/user/:id',\n  handler: (ctx) =\u003e {\n    ctx.body = {\n      /* payload here */\n    };\n  },\n  validate: {\n    params: z.object({ id: z.coerce.number() }),\n    response: z.object({\n      /* validation here */\n    }),\n  },\n});\n```\n\n`index.ts:`\n\n```js\nimport zodRouter from 'koa-zod-router';\nimport { getUserRoute } from './get-user.ts';\n\nconst router = zodRouter();\nrouter.register(getUserRoute);\n```\n\n### Adding state to routes\n\nzodRouter accepts a type parameter for adding types to `ctx.state`, as well as providing a helper function used creating routes and middlewares with state types.\n\n`route-state.ts:`\n\n```js\nimport { routerSpecFactory } from 'koa-zod-router';\n\nexport type UserState = {\n  user: {\n    username: string;\n    email: string;\n    id: number;\n  };\n};\n\nexport const specFactory = routerSpecFactory\u003cUserState\u003e();\n\n```\n\n`auth-middleware.ts:`\n\n```js\nimport { z } from 'zod';\nimport { specFactory } from './route-state';\n\nexport const authMiddleware = specFactory.createUseSpec({\n  handler: async (ctx, next) =\u003e {\n    // ... validate the session token\n\n    // setting state is now typesafe\n    ctx.state.user = {\n      username: 'johndoe',\n      email: 'example@email.com',\n      id: 1,\n    };\n\n    await next();\n  },\n  validate: {\n    // validation fails if `x-session-token` is not set in the HTTP request headers\n    headers: z.object({ 'x-session-token': z.string() }),\n  },\n});\n```\n\n`get-user.ts:`\n\n```js\nimport { z } from 'zod';\nimport { specFactory } from './route-state';\n\nexport const getUserRoute = specFactory.createRouteSpec({\n  method: 'get',\n  path: '/user/:id',\n  handler: async (ctx) =\u003e {\n    //.. our route has access to the ctx.state.user types now\n    ctx.state.user;\n  },\n  validate: {\n    /* validation here */\n  },\n});\n```\n\n`index.ts:`\n\n```js\nimport zodRouter from 'koa-zod-router';\nimport { UserState } from './router-state';\nimport { authMiddleware } from './auth-middleware';\nimport { getUserRoute } from './get-user';\n\nconst router = zodRouter\u003cUserState\u003e();\n\nrouter.use(authMiddleware);\nrouter.register(getUserRoute);\n```\n\n### Exposing validation errors to the client\n\nBy default validation errors will respond with either a generic 400 or 500 error depending on whether the validation fails from the sent fields in the request, or if there is an issue in the response body.\n\nTo enable ZodErrors being exposed to the client simply use the following config:\n\n```js\nconst router = zodRouter({\n  zodRouter: { exposeRequestErrors: true, exposeResponseErrors: true },\n});\n```\n\n### Type coercion\n\nWhen dealing with route parameters, query strings, and headers the incoming data will be parsed as strings to begin with. From a validation standpoint this can potentially be painful to deal with when dealing with things like `Date` in javascript. Luckily [zod] has a built in [coercion] method attached to its primitive data types to solve this!\n\n**convert a route parameter to a number:**\n\n```js\nrouter.register({\n  path: '/users/:id',\n  method: 'get',\n  handler: async (ctx) =\u003e {\n    console.log(typeof ctx.request.params.id);\n    // 'number'\n  },\n  validate: {\n    params: z.object({ id: z.coerce.number() }),\n  },\n});\n```\n\n### Dealing with dates\n\nAs mentioned above type coercion can be very useful in a lot of situations, especially when dealing with dates. Since `Date` cannot be passed directly into JSON we must convert both the data received and the data being sent back to the client. Avoid using `z.date()` in your schemas as these will result in validation errors. Instead use `z.coerce.date()` for input data, and `z.string()` (or your choice of primitive data-type) for output.\n\n```js\nrouter.register({\n  path: '/date',\n  method: 'post',\n  handler: async (ctx) =\u003e {\n    const { date } = ctx.request.body;\n    console.log(date instanceof Date);\n    // true\n    ctx.body = {\n      date: date.toISOString(),\n    };\n  },\n  validate: {\n    body: z.object({ date: z.coerce.date() }), // converts received string or number into date object\n    response: z.object({ date: z.string() }),\n  },\n});\n```\n\n### Dealing with files\n\nkoa-zod-router uses [formidable] for any requests received with the `Content-Type` header set to `multipart/*`.\n\nThis functionality is disabled by default, to enable this functionality create an instance of zodRouter and pass in `{ zodRouter: { enableMultipart: true } }` as your config. Then to validate files utilize the helper function `zFile`.\n\n```js\nimport zodRouter, { zFile } from 'koa-zod-router';\n\nconst fileRouter = zodRouter({ zodRouter: { enableMultipart: true } });\n\nfileRouter.register({\n  path: '/uploads',\n  method: 'post',\n  handler: async (ctx) =\u003e {\n    const { file_one, multiple_files } = ctx.request.files;\n    //...\n  },\n  validate: {\n    body: z.object({ hello: z.string() }),\n    files: z.object({\n      file_one: zFile(),\n      multiple_files: z.array(zFile()).or(zFile()),\n    }),\n  },\n});\n```\n\n## Custom Validation Error Handling\n`koa-zod-router` allows users to implement router-wide error handling or route specific error handling. \n\n### Router-wide error handling\n\nBy passing a function `validationErrorHandler` into `zodRouter` options you can execute an error handler that occurs immediately after the validation-middleware does it's thing.\n\n```js\nimport { ValidationErrorHandler } from 'koa-zod-router';\n\nconst validationErrorHandler: ValidationErrorHandler = async (ctx, next) =\u003e {\n  if (ctx.invalid.error) {\n    ctx.status = 400;\n    ctx.body = 'hello';\n  } else {\n    await next();\n  }\n\n  return;\n};\n\nconst router = zodRouter({\n  zodRouter: { exposeResponseErrors: true, validationErrorHandler },\n});\n```\n\n### Route specific error handling\nBy enabling `continueOnError` you can bypass the default error handling done by the router's validation middleware and handle the errors the way you see fit.\n\n```js\nimport zodRouter from 'koa-zod-router';\nimport { z } from 'zod';\n\nconst router = zodRouter();\n\n//... create a custom error handler\n\nrouter.register({\n  method: 'get',\n  path: '/foo',\n  handler: [\n    // error handler\n    async (ctx, next) =\u003e {\n      // check if an error was thrown\n      if (ctx.invalid.error) {\n        // destructure all of the ZodErrors from ctx.invalid\n        const { body, headers, query, params, files } = ctx.invalid;\n        //... handle ZodErrors\n      } else {\n        await next();\n      }\n    },\n    async (ctx, next) =\u003e {\n      // .. route handler\n    },\n  ],\n  validate: {\n    continueOnError: true,\n    body: z.object({\n      foo: z.string(),\n    }),\n  },\n});\n```\n\n## API Reference\n\n[Reference](https://github.com/JakeFenley/koa-zod-router/tree/main/docs/API.md)\n\n## Feedback\n\nFound a bug?\nPlease let me know in [Issues section](https://github.com/JakeFenley/koa-zod-router/issues).\n\nHave a question or idea?\nPlease let me know in [Discussions section](https://github.com/JakeFenley/koa-zod-router/discussions).\n\nFound a vulnerability or other security issue?\nPlease refer to [Security policy](https://github.com/JakeFenley/koa-zod-router/blob/main/SECURITY.md).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjakefenley%2Fkoa-zod-router","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjakefenley%2Fkoa-zod-router","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjakefenley%2Fkoa-zod-router/lists"}