{"_id":"@ai0x0/next-rest-framework","name":"@ai0x0/next-rest-framework","dist-tags":{"latest":"6.2.0"},"versions":{"6.2.0":{"name":"@ai0x0/next-rest-framework","version":"6.2.0","description":"Type-safe, self-documenting APIs for Next.js — AI0x0 的维护分支（fork of next-rest-framework by Markus Blomqvist）","keywords":["nextjs","rest","api","next-rest-framework"],"homepage":"https://next-rest-framework.vercel.app","bugs":{"url":"https://github.com/AI0x0/next-rest-framework/issues"},"license":"ISC","author":{"name":"Markus Blomqvist","email":"blomqma@omg.lol"},"main":"dist/index.js","module":"dist/index.mjs","types":"dist/index.d.ts","repository":{"type":"git","url":"git+https://github.com/AI0x0/next-rest-framework.git","directory":"packages/next-rest-framework"},"bin":{"next-rest-framework":"dist/cli/index.js"},"dependencies":{"chalk":"4.1.2","commander":"10.0.1","formidable":"^3.5.1","lodash":"4.18.1","prettier":"3.0.2","qs":"6.15.1"},"peerDependencies":{"zod":"^4.0.0"},"devDependencies":{"@types/formidable":"^3.4.5","@types/jest":"29.5.4","@types/lodash":"4.14.197","@types/qs":"6.9.11","esbuild":"0.19.11","jest":"29.6.4","next":"*","node-mocks-http":"1.13.0","openapi-types":"12.1.3","ts-jest":"29.1.1","ts-node":"10.9.1","tsup":"8.0.1","typescript":"*","zod":"^4.1.13","zod-form-data":"3.0.1"},"publishConfig":{"access":"public"},"scripts":{"lint":"tsc","test":"jest","test:watch":"jest --watch","build":"tsup --dts"},"_id":"@ai0x0/next-rest-framework@6.2.0","_integrity":"sha512-FwbAsSrwxKrzrzEv4InBFnUm5vfYomSxpgWgnDl2HhoeXzqh58eAp5BGCPOnKEZW/zhPz2UHogyWkafdUEusFQ==","_resolved":"/tmp/62158d962e0d98ee2accdfb769e47036/ai0x0-next-rest-framework-6.2.0.tgz","_from":"file:ai0x0-next-rest-framework-6.2.0.tgz","_nodeVersion":"20.20.2","_npmVersion":"10.8.2","dist":{"integrity":"sha512-FwbAsSrwxKrzrzEv4InBFnUm5vfYomSxpgWgnDl2HhoeXzqh58eAp5BGCPOnKEZW/zhPz2UHogyWkafdUEusFQ==","shasum":"0f4574d2ba88294e185ffddccd6cfbe2791fe48b","tarball":"https://registry.npmjs.org/@ai0x0/next-rest-framework/-/next-rest-framework-6.2.0.tgz","fileCount":38,"unpackedSize":882890,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEQCIGmbx1qBZeelgaBIhVDB0xX4F5h+JRMpcRlQdBb1LwmNAiAL2aJDl870IKZYkGi3mt8aZ6mrLgRlhpU1unZbEgqbfQ=="}]},"_npmUser":{"name":"mushan01","email":"MuShan0x0@gmail.com"},"directories":{},"maintainers":[{"name":"mushan01","email":"MuShan0x0@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/next-rest-framework_6.2.0_1787899197889_0.30044499233813204"},"_hasShrinkwrap":false}},"time":{"created":"2026-08-28T06:39:57.762Z","6.2.0":"2026-08-28T06:39:58.071Z","modified":"2026-08-28T06:39:58.326Z"},"maintainers":[{"name":"mushan01","email":"MuShan0x0@gmail.com"}],"description":"Type-safe, self-documenting APIs for Next.js — AI0x0 的维护分支（fork of next-rest-framework by Markus Blomqvist）","homepage":"https://next-rest-framework.vercel.app","keywords":["nextjs","rest","api","next-rest-framework"],"repository":{"type":"git","url":"git+https://github.com/AI0x0/next-rest-framework.git","directory":"packages/next-rest-framework"},"author":{"name":"Markus Blomqvist","email":"blomqma@omg.lol"},"bugs":{"url":"https://github.com/AI0x0/next-rest-framework/issues"},"license":"ISC","readme":"<p align=\"center\">\n  <br/>\n  <img width=\"250px\" src=\"https://raw.githubusercontent.com/blomqma/next-rest-framework/d02224b38d07ede85257b22ed50159a947681f99/packages/next-rest-framework/logo.svg\" />\n  <h2 align=\"center\">Next REST Framework</h3>\n  <p align=\"center\">Type-safe, self-documenting APIs for Next.js</p>\n  <br/>\n  <p align=\"center\">\n    <a href=\"https://github.com/blomqma/next-rest-framework/actions?query=branch%3Amain\">\n      <img src=\"https://github.com/blomqma/next-rest-framework/actions/workflows/ci.yml/badge.svg?event=push&branch=main\" alt=\"CI status\" />\n    </a>\n    <a href=\"https://codecov.io/gh/blomqma/next-rest-framework\" >\n      <img src=\"https://codecov.io/gh/blomqma/next-rest-framework/branch/main/graph/badge.svg?token=IUG5ZCVGPV\"/>\n    </a>\n    <a href=\"https://github.com/blomqma/next-rest-framework/stargazers\">\n      <img src=\"https://img.shields.io/github/stars/blomqma/next-rest-framework\" alt=\"Github Stars\" />\n    </a>\n    <a href=\"https://opensource.org/licenses/ISC\" rel=\"nofollow\">\n      <img src=\"https://img.shields.io/badge/License-ISC-blue.svg\" alt=\"License\">\n    </a>\n    <img src=\"https://img.shields.io/badge/Contributor%20Covenant-2.1-4baaaa.svg\" alt=\"Contributor Covenant 2.1\" />\n  </p>\n</p>\n\n## Table of contents\n\n- [Table of contents](#table-of-contents)\n- [Overview](#overview)\n- [AI Assistant Skill](#ai-assistant-skill)\n- [Features](#features)\n  - [Lightweight, type-safe, easy to use](#lightweight-type-safe-easy-to-use)\n- [Requirements](#requirements)\n- [Installation](#installation)\n- [Getting started](#getting-started)\n  - [Create docs endpoint](#create-docs-endpoint)\n    - [App router docs route:](#app-router-docs-route)\n    - [Pages router docs API route:](#pages-router-docs-api-route)\n  - [Create endpoint](#create-endpoint)\n    - [REST endpoints](#rest-endpoints)\n      - [App router route:](#app-router-route)\n      - [Pages router API route:](#pages-router-api-route)\n    - [Form endpoints](#form-endpoints)\n      - [App router form route:](#app-router-form-route)\n      - [Pages router form API route:](#pages-router-form-api-route)\n    - [RPC endpoints](#rpc-endpoints)\n      - [App router RPC route:](#app-router-rpc-route)\n      - [Pages router RPC API route:](#pages-router-rpc-api-route)\n  - [Client](#client)\n    - [REST client](#rest-client)\n    - [RPC client](#rpc-client)\n- [API reference](#api-reference)\n  - [Docs handler options](#docs-handler-options)\n  - [Docs config](#docs-config)\n  - [REST](#rest)\n    - [Route handler options](#route-handler-options)\n    - [Route operations](#route-operations)\n      - [Route operation input](#route-operation-input)\n      - [Route operation outputs](#route-operation-outputs)\n      - [Route operation middleware](#route-operation-middleware)\n      - [Route operation handler](#route-operation-handler)\n  - [RPC](#rpc)\n    - [RPC route handler options](#rpc-route-handler-options)\n    - [RPC operations](#rpc-operations)\n      - [RPC operation input](#rpc-operation-input)\n      - [RPC operation outputs](#rpc-operation-outputs)\n      - [RPC operation middleware](#rpc-operation-middleware)\n      - [RPC operation handler](#rpc-operation-handler)\n- [CLI](#cli)\n- [Changelog](#changelog)\n- [Contributing](#contributing)\n- [License](#license)\n\n## [Overview](#overview)\n\nNext REST Framework is an open-source, opinionated, lightweight, easy-to-use set of tools to build type-safe, self-documenting APIs with [Next.js](http://nextjs.org/). Building OpenAPI specification-compliant APIs can be cumbersome and slow but Next REST Framework makes this easy with auto-generated OpenAPI documents and docs using TypeScript and object schemas.\n\n- [Live demo](https://next-rest-framework-demo.vercel.app)\n- [Docs](https://next-rest-framework.vercel.app)\n\n## [AI Assistant Skill](#ai-assistant-skill)\n\nThis repository ships an agent skill at `skills/create-next-rest-framework-api`, installable with the [`skills` CLI](https://github.com/vercel-labs/skills).\n\nInstall:\n\n```bash\nnpx skills add blomqma/next-rest-framework --skill create-next-rest-framework-api\n```\n\nInstall globally instead of per-project:\n\n```bash\nnpx skills add blomqma/next-rest-framework --skill create-next-rest-framework-api --global\n```\n\nThis is a monorepo containing the following packages / projects:\n\n1. The primary `next-rest-framework` package\n2. An example application for live demo and local development\n\n## [Features](#features)\n\n### Lightweight, type-safe, easy to use\n\n- Designed to work with TypeScript so that your requests and responses are strongly typed.\n- Supports API endpoints using both RESTful and RPC principles.\n- Object-schema validation with [Zod](https://github.com/colinhacks/zod). The object schemas are automatically converted to JSON schema format for the auto-generated OpenAPI specification.\n- Auto-generated and extensible `openapi.json` spec file from your business logic.\n- Auto-generated [Redoc](https://github.com/Redocly/redoc) and/or [SwaggerUI](https://swagger.io/tools/swagger-ui/) documentation frontend.\n- Works with Next.js [Middleware](https://nextjs.org/docs/app/building-your-application/routing/middleware) and other server-side libraries, like [NextAuth.js](#https://github.com/nextauthjs/next-auth).\n- Supports both Next.js [app router](https://nextjs.org/docs/app/building-your-application/routing#the-app-router) and [pages router](https://nextjs.org/docs/pages/building-your-application/routing), even at the same time.\n- Supports [Edge runtime](https://nextjs.org/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes).\n- Fully customizable and compatible with any existing Next.js project.\n\n## Requirements\n\n- Node.js v18.x. If you have an API using `File` or `FormData` web APIs, you might need Node v20.x, see: https://github.com/vercel/next.js/discussions/56032\n\nYou also need the following dependencies installed in you Next.js project:\n\n- [Next.js](https://github.com/vercel/next.js) >= v12\n- Optional (needed for validating input): [Zod](https://github.com/colinhacks/zod) >= v3\n- Optional: [TypeScript](https://www.typescriptlang.org/) >= v3\n- Optional (needed when using the CLI commands and using TypeScript): [tsx](https://github.com/privatenumber/tsx) >= v4\n- Optional (needed if working with forms): [zod-form-data](https://www.npmjs.com/package/zod-form-data) >= v2\n\n## [Installation](#installation)\n\n```sh\nnpm install next-rest-framework\n```\n\n## [Getting started](#getting-started)\n\n### [Create docs endpoint](#create-docs-endpoint)\n\nTo get access to the auto-generated documentation, initialize the docs endpoint somewhere in your codebase. You can also skip this step if you don't want to expose a public API documentation.\n\n#### [App router docs route](#app-router-docs-route):\n\n```typescript\n// src/app/api/v2/route.ts\n\nimport { docsRoute } from 'next-rest-framework';\n\n// export const runtime = 'edge'; // Edge runtime is supported.\n\nexport const { GET } = docsRoute({\n  // deniedPaths: [...] // Ignore endpoints from the generated OpenAPI spec.\n  // allowedPaths: [...], // Explicitly set which endpoints to include in the generated OpenAPI spec.\n  // Override and customize the generated OpenAPI spec.\n  openApiObject: {\n    info: {\n      title: 'My API',\n      version: '1.0.0',\n      description: 'My API description.'\n    }\n    // ...\n  },\n  // openApiJsonPath: '/openapi.json', // Customize the path where the OpenAPI spec will be generated.\n  // Customize the rendered documentation.\n  docsConfig: {\n    provider: 'redoc', // redoc | swagger-ui\n    title: 'My API',\n    description: 'My API description.'\n    // ...\n  }\n});\n```\n\n#### [Pages router docs API route](#pages-router-docs-api-route):\n\n```typescript\n// src/pages/api/v1/index.ts\n\nimport { docsApiRoute } from 'next-rest-framework';\n\nexport default docsApiRoute({\n  // See configuration options from above.\n});\n```\n\nThis is enough to get you started. Now you can access the API documentation in your browser. Running `npx next-rest-framework generate` in the project root will generate the `openapi.json` OpenAPI specification file, located in the `public` folder by default. You can create multiple docs endpoints if needed and specify which config to use for the [CLI](#cli). See the full configuration options of this endpoint in the [Docs handler options](#docs-handler-options) section.\n\n### [Create endpoint](#create-endpoint)\n\n#### [REST endpoints](#rest-endpoints)\n\n##### [App router route](#app-router-route):\n\n```typescript\n// src/app/api/v2/todos/route.ts\n\nimport { TypedNextResponse, route, routeOperation } from 'next-rest-framework';\nimport { z } from 'zod';\n\n// export const runtime = 'edge'; // Edge runtime is supported.\n\nconst MOCK_TODOS = [\n  {\n    id: 1,\n    name: 'TODO 1',\n    completed: false\n  }\n  // ...\n];\n\nconst todoSchema = z.object({\n  id: z.number(),\n  name: z.string(),\n  completed: z.boolean()\n});\n\nexport const { GET, POST } = route({\n  getTodos: routeOperation({\n    method: 'GET'\n  })\n    .outputs([\n      {\n        status: 200,\n        contentType: 'application/json',\n        body: z.array(todoSchema)\n      }\n    ])\n    .handler(() => {\n      return TypedNextResponse.json(MOCK_TODOS, {\n        status: 200\n      });\n    }),\n\n  createTodo: routeOperation({\n    method: 'POST'\n  })\n    .input({\n      contentType: 'application/json',\n      body: z.object({\n        name: z.string()\n      })\n    })\n    .outputs([\n      {\n        status: 201,\n        contentType: 'application/json',\n        body: z.string()\n      },\n      {\n        status: 401,\n        contentType: 'application/json',\n        body: z.string()\n      }\n    ])\n    // Optional middleware logic executed before request validation.\n    .middleware((req) => {\n      if (!req.headers.get('very-secure')) {\n        return TypedNextResponse.json('Unauthorized', {\n          status: 401\n        });\n      }\n    })\n    .handler(async (req) => {\n      const { name } = await req.json();\n\n      return TypedNextResponse.json(`New TODO created: ${name}`, {\n        status: 201\n      });\n    })\n});\n```\n\nThe `TypedNextResponse` ensures that the response status codes and content-type headers are type-checked against the defined outputs. You can still use the regular `NextResponse` if you prefer to have less type-safety.\n\n##### [Pages router API route](#pages-router-api-route):\n\n```typescript\n// src/pages/api/v1/todos/index.ts\n\nimport { apiRoute, apiRouteOperation } from 'next-rest-framework';\nimport { z } from 'zod';\n\nconst MOCK_TODOS = [\n  {\n    id: 1,\n    name: 'TODO 1',\n    completed: false\n  }\n  // ...\n];\n\nconst todoSchema = z.object({\n  id: z.number(),\n  name: z.string(),\n  completed: z.boolean()\n});\n\nexport default apiRoute({\n  getTodos: apiRouteOperation({\n    method: 'GET'\n  })\n    .outputs([\n      {\n        status: 200,\n        contentType: 'application/json',\n        body: z.array(todoSchema)\n      }\n    ])\n    .handler((_req, res) => {\n      res.status(200).json(MOCK_TODOS);\n    }),\n\n  createTodo: apiRouteOperation({\n    method: 'POST'\n  })\n    .input({\n      contentType: 'application/json',\n      body: z.object({\n        name: z.string()\n      })\n    })\n    .outputs([\n      {\n        status: 201,\n        contentType: 'application/json',\n        body: z.string()\n      },\n      {\n        status: 401,\n        contentType: 'application/json',\n        body: z.string()\n      }\n    ])\n    // Optional middleware logic executed before request validation.\n    .middleware((req, res) => {\n      if (!req.headers['very-secure']) {\n        res.status(401).json('Unauthorized');\n      }\n    })\n    .handler((req, res) => {\n      const { name } = req.body;\n      // Create a new TODO.\n      res.status(201).json(`New TODO created: ${name}`);\n    })\n});\n```\n\nAfter running `next-rest-framework generate`, all of above type-safe endpoints will be auto-generated to your OpenAPI spec and exposed in the documentation:\n\n![Next REST Framework docs](./docs/static/img/docs-screenshot.jpg)\n\n#### [Form endpoints](#form-endpoints)\n\n##### [App router form route](#app-router-form-route):\n\nWhen specifying request input schema for validation, the content type header determines what kind of schema you can use to validate the request body.\nWhen using `application/json`, a plain Zod object schema can be used for the validation. When using `application/x-www-form-urlencoded` or `multipart/form-data` content types, a [zod-form-data](https://www.npmjs.com/package/zod-form-data) schema must be used:\n\n```typescript\n// src/app/api/v2/form-data/url-encoded/route.ts\n\nimport { TypedNextResponse, route, routeOperation } from 'next-rest-framework';\nimport { zfd } from 'zod-form-data';\n\n// export const runtime = 'edge'; // Edge runtime is supported.\n\nconst formSchema = zfd.formData({\n  text: zfd.text()\n});\n\nexport const { POST } = route({\n  urlEncodedFormData: routeOperation({\n    method: 'POST'\n  })\n    .input({\n      contentType: 'application/x-www-form-urlencoded',\n      body: formSchema // A zod-form-data schema is required.\n    })\n    .outputs([\n      {\n        status: 200,\n        contentType: 'application/octet-stream',\n        body: formSchema\n      }\n    ])\n    .handler(async (req) => {\n      const { text } = await req.json();\n      // const formData = await req.formData(); // Form can also be parsed as form data.\n\n      // Type-checked response.\n      return TypedNextResponse.json({\n        text\n      });\n    })\n});\n```\n\nFor `multipart/form-data` app router example, see [this example](https://github.com/blomqma/next-rest-framework/tree/main/apps/example/src/app/api/v2/form-data/multipart/route.ts).\n\n##### [Pages router form API route](#pages-router-form-api-route):\n\nA form API route with pages router works similarly as the [App router form route](#app-router-form-route) using a `zod-form-data` schema:\n\n```typescript\n// src/pages/api/v1/form-data/url-encoded/index.ts\n\nimport { apiRoute, apiRouteOperation } from 'next-rest-framework';\nimport { zfd } from 'zod-form-data';\n\nconst formSchema = zfd.formData({\n  text: zfd.text()\n});\n\nexport default apiRoute({\n  urlEncodedFormData: apiRouteOperation({\n    method: 'POST'\n  })\n    .input({\n      contentType: 'application/x-www-form-urlencoded',\n      body: formSchema // A zod-form-data schema is required.\n    })\n    .outputs([\n      {\n        status: 200,\n        contentType: 'application/json',\n        body: formSchema\n      }\n    ])\n    .handler((req, res) => {\n      const formData = req.body;\n\n      res.json({\n        text: formData.get('text')\n      });\n    })\n});\n```\n\nFor `multipart/form-data` pages router example, see [this example](https://github.com/blomqma/next-rest-framework/tree/main/apps/example/pages/api/v1/form-data/multipart/index.ts/form-data/multipart/index.ts).\n\nThe form routes will also be included in your OpenAPI spec after running `next-rest-framework generate`.\n\n#### [RPC endpoints](#rpc-endpoints)\n\nNext REST Framework also supports writing RPC-styled APIs that support JSON and form data. A recommended way is to write your RPC operations in a separate server-side module where they can be consumed both by the RPC endpoints and directly as server-side functions (server actions):\n\n```typescript\n// src/app/actions.ts\n\n'use server';\n\nimport { rpcOperation } from 'next-rest-framework';\nimport { z } from 'zod';\nimport { zfd } from 'zod-form-data';\n\n// The RPC operations can be used as server-actions and imported in the RPC route handlers.\n\nconst MOCK_TODOS = [\n  {\n    id: 1,\n    name: 'TODO 1',\n    completed: false\n  }\n  // ...\n];\n\nconst todoSchema = z.object({\n  id: z.number(),\n  name: z.string(),\n  completed: z.boolean()\n});\n\nexport const getTodos = rpcOperation()\n  .outputs([\n    {\n      body: z.array(todoSchema)\n    }\n  ])\n  .handler(() => {\n    return MOCK_TODOS;\n  });\n\nexport const getTodoById = rpcOperation()\n  .input({\n    contentType: 'application/json',\n    body: z.string()\n  })\n  .outputs([\n    {\n      body: z.object({\n        error: z.string()\n      })\n    },\n    {\n      body: todoSchema\n    }\n  ])\n  .handler((id) => {\n    const todo = MOCK_TODOS.find((t) => t.id === Number(id));\n\n    if (!todo) {\n      return { error: 'TODO not found.' };\n    }\n\n    return todo;\n  });\n\nexport const createTodo = rpcOperation()\n  .input({\n    contentType: 'application/json',\n    body: z.object({\n      name: z.string()\n    })\n  })\n  .outputs([{ body: todoSchema }])\n  .handler(async ({ name }) => {\n    const todo = { id: 4, name, completed: false };\n    return todo;\n  });\n\nexport const deleteTodo = rpcOperation()\n  .input({\n    contentType: 'application/json',\n    body: z.string()\n  })\n  .outputs([\n    { body: z.object({ error: z.string() }) },\n    { body: z.object({ message: z.string() }) }\n  ])\n  .handler((id) => {\n    const todo = MOCK_TODOS.find((t) => t.id === Number(id));\n\n    if (!todo) {\n      return {\n        error: 'TODO not found.'\n      };\n    }\n\n    return { message: 'TODO deleted.' };\n  });\n\nconst formSchema = zfd.formData({\n  text: zfd.text()\n});\n\nexport const formDataUrlEncoded = rpcOperation()\n  .input({\n    contentType: 'application/x-www-form-urlencoded',\n    body: formSchema // A zod-form-data schema is required.\n  })\n  .outputs([{ body: formSchema }])\n  .handler((formData) => {\n    return {\n      text: formData.get('text')\n    };\n  });\n\nconst multipartFormSchema = zfd.formData({\n  text: zfd.text(),\n  file: zfd.file()\n});\n\nexport const formDataMultipart = rpcOperation()\n  .input({\n    contentType: 'multipart/form-data',\n    body: multipartFormSchema // A zod-form-data schema is required.\n  })\n  .outputs([\n    {\n      body: z.custom<File>(),\n      // The binary file cannot described with a Zod schema so we define it by hand for the OpenAPI spec.\n      bodySchema: {\n        type: 'string',\n        format: 'binary'\n      }\n    }\n  ])\n  .handler((formData) => {\n    const file = formData.get('file');\n    return file;\n  });\n```\n\nNow you can consume the RPC operations directly in your server-side components:\n\n```typescript\n'use server';\n\nimport { getTodos, createTodo } from 'src/app/actions';\n\nexport default async function Page() {\n  const todos = await getTodos();\n\n  const createTodo = async (name: string) => {\n    'use server';\n    return createTodo({ name });\n  };\n\n  // ...\n}\n```\n\n##### [App router RPC route](#app-router-rpc-route):\n\nThe file path to an RPC route must end with `/[operationId]/route.ts`. Simply import the RPC operations in to your RPC route handler:\n\n```typescript\n// src/app/api/rpc/[operationId]/route.ts\n\nimport {\n  createTodo,\n  deleteTodo,\n  getTodoById,\n  getTodos,\n  formDataUrlEncoded,\n  formDataMultipart\n} from 'src/app/actions';\nimport { rpcRoute } from 'next-rest-framework';\n\n// export const runtime = 'edge'; // Edge runtime is supported.\n\nexport const { POST } = rpcRoute({\n  getTodos,\n  getTodoById,\n  createTodo,\n  deleteTodo,\n  formDataUrlEncoded,\n  formDataMultipart\n  // You can also inline the RPC operations in this object if you don't need to use server actions.\n});\n\nexport type RpcClient = typeof POST.client;\n```\n\n##### [Pages router RPC API route](#pages-router-rpc-api-route):\n\nThe filename of an RPC API route must be `[operationId].ts`.\n\n```typescript\n// src/pages/api/rpc/[operationId].ts\n\nimport { rpcApiRoute } from 'next-rest-framework';\n// import { ... } from 'src/app/actions';\n\nconst handler = rpcApiRoute({\n  // ...\n  // Exactly the same as the app router example above.\n});\n\nexport default handler;\n\nexport type RpcClient = typeof handler.client;\n```\n\nThe RPC routes will also be included in your OpenAPI spec after running `next-rest-framework generate`.\n\n### [Client](#client)\n\n#### [REST client](#rest-client)\n\nTo achieve end-to-end type-safety with your REST endpoints, you can use any client implementation that relies on the generated OpenAPI specification, e.g. [openapi-client-axios](https://github.com/openapistack/openapi-client-axios).\n\n#### [RPC client](#rpc-client)\n\nWhile you can consume your RPC operations directly as server actions in your React server components, for client-rendered components you can use the strongly-typed `rpcClient`, passing in the exported type from your RPC endpoint as a generic parameter:\n\n```typescript\n'use client';\n\nimport { rpcClient } from 'next-rest-framework/rpc-client';\nimport { type RpcClient } from 'app/api/rpc/[operationId]';\n\nconst client = rpcClient<RpcClient>({\n  url: 'http://localhost:3000/api/rpc'\n});\n\nexport default function Page() {\n  // ...\n\n  useEffect(() => {\n    client\n      .getTodos()\n      .then(() => {\n        // ...\n      })\n      .catch(console.error);\n  }, []);\n\n  const createTodo = async (name: string) => {\n    const todo = client.createTodo({ name });\n    // ...\n  };\n\n  // ...\n}\n```\n\nThe `rpcClient` calls can also be easily integrated with any data fetching framework, like React Query or RTKQ.\n\n## [API reference](#api-reference)\n\n### [Docs handler options](#docs-handler-options)\n\nThe following options can be passed to the `docsRoute` (app router) and `docsApiRoute` (pages router) functions for customizing Next REST Framework:\n\n| Name              | Description                                                                                                                                                                                                                                                                                                            |\n| ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `deniedPaths`     | Array of paths that are denied by Next REST Framework and not included in the OpenAPI spec. Supports wildcards using asterisk `*` and double asterisk `**` for recursive matching. Example: `['/api/disallowed-path', '/api/disallowed-path-2/*', '/api/disallowed-path-3/**']` Defaults to no paths being disallowed. |\n| `allowedPaths`    | Array of paths that are allowed by Next REST Framework and included in the OpenAPI spec. Supports wildcards using asterisk `*` and double asterisk `**` for recursive matching. Example: `['/api/allowed-path', '/api/allowed-path-2/*', '/api/allowed-path-3/**']` Defaults to all paths being allowed.               |\n| `openApiObject`   | An [OpenAPI Object](https://swagger.io/specification/#openapi-object) that can be used to override and extend the auto-generated specification.                                                                                                                                                                        |\n| `openApiJsonPath` | Path that will be used for fetching the OpenAPI spec - defaults to `/openapi.json`. This path also determines the path where this file will be generated inside the `public` folder.                                                                                                                                   |\n| `docsConfig`      | A [Docs config](#docs-config) object for customizing the generated docs.                                                                                                                                                                                                                                               |\n\n### [Docs config](#docs-config)\n\nThe docs config options can be used to customize the generated docs:\n\n| Name          | Description                                                                                                                                  |\n| ------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |\n| `provider`    | Determines whether to render the docs using Redoc (`redoc`) or SwaggerUI `swagger-ui`. Defaults to `redoc`.                                  |\n| `title`       | Custom title, used for the visible title and HTML title.                                                                                     |\n| `description` | Custom description, used for the visible description and HTML meta description.                                                              |\n| `faviconUrl`  | Custom HTML meta favicon URL.                                                                                                                |\n| `logoUrl`     | A URL for a custom logo.                                                                                                                     |\n| `ogConfig`    | [Basic customization options](https://ogp.me/#metadata) for OG meta tags. Requires the following fields: `title`, `type`, `url`, `imageUrl`. |\n\n### REST\n\n#### [Route handler options](#route-handler-options)\n\nThe `routeHandler` (app router) and `apiRouteHandler` (pages router) functions allow you to pass an object as the second parameter, where you can define a property called `openApiPath`. This property is an OpenAPI [Path Item Object](https://swagger.io/specification/#path-item-object) that can be used to override and extend the auto-generated specification for the given route.\n\n#### [Route operations](#route-operations)\n\nThe route operation functions `routeOperation` (app router) and `apiRouteOperation` (pages router) allow you to define your method handlers for your endpoints. These functions require you to pass an object where you will define the method for the given operation, as well as optionally a property called `openApiOperation`. This property is an OpenAPI [Operation object](https://swagger.io/specification/#operation-object) that can be used to override and extend the auto-generated specification for the given operation. Calling the `routeOperation` and `apiRouteOperation` functions allows you to chain your API handler logic with the following functions:\n\n| Name         | Description                                                                                                                                                                                                                                                          |\n| ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `input`      | A [Route operation input](#route-operation-input) function for defining the validation and documentation of the request.                                                                                                                                             |\n| `outputs`    | An [Route operation outputs](#route-operation-outputs) function for defining the validation and documentation of the response.                                                                                                                                       |\n| `handler`    | A [Route operation-handler](#route-operation-handler) function for defining your business logic.                                                                                                                                                                     |\n| `middleware` | A [Route operation middleware](#route-operation-middleware) function that gets executed before the request input is validated. You may chain up to three middlewares together and share data between the middlewares by taking the input of the previous middleware. |\n\n##### [Route operation input](#route-operation-input)\n\nThe route operation input function is used for type-checking, validation and documentation of the request, taking in an object with the following properties:\n\n| Name          | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                            | Required |\n| ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- |\n| `contentType` | The content type header of the request. When the content type is defined, a request with an incorrect content type header will get an error response.                                                                                                                                                                                                                                                                                                                  | `false`  |\n| `body`        | A [Zod](https://github.com/colinhacks/zod) schema describing the format of the request body. When using `application/x-www-form-urlencoded` or `multipart/form-data` content types, this should be a `zod-form-data` schema instead. When the body schema is defined, a request with an invalid request body will get an error response. The request body is parsed using this schema and updated to the request if valid, so the body should always match the schema. | `false`  |\n| `bodySchema`  | A JSON schema that you can provide in case the conversion of the `body` Zod schema fails or produces an incorrect result in your OpenAPI spec.                                                                                                                                                                                                                                                                                                                         | `false`  |\n| `query`       | A [Zod](https://github.com/colinhacks/zod) schema describing the format of the query parameters. When the query schema is defined, a request with invalid query parameters will get an error response. Query parameters are parsed using this schema and updated to the request if valid, so the query parameters from the request should always match the schema.                                                                                                     | `false`  |\n| `querySchema` | A JSON schema that you can provide in case the conversion of the `query` Zod schema fails or produces an incorrect result in your OpenAPI spec.                                                                                                                                                                                                                                                                                                                        | `false`  |\n| `params`      | A [Zod](https://github.com/colinhacks/zod) schema describing the format of the path parameters. When the params schema is defined, a request with invalid path parameters will get an error response. Path parameters are parsed using this schema and updated to the request if valid, so the path parameters from the request should always match the schema.                                                                                                        | `false`  |\n\nCalling the route operation input function allows you to chain your API handler logic with the [Route operation outputs](#route-operation-outputs), [Route operation middleware](#route-operation-middleware) and [Route operation handler](#route-operation-handler) functions.\n\n##### [Route operation outputs](#route-operation-outputs)\n\nThe route operation outputs function is used for type-checking and documentation of the response, taking in an array of objects with the following properties:\n\n| Name          | Description                                                                                                                                    | Required |\n| ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | -------- |\n| `status`      | A status code that your API can return.                                                                                                        | `true`   |\n| `contentType` | The content type header of the response.                                                                                                       | `true`   |\n| `body`        | A [Zod](https://github.com/colinhacks/zod) (or `zod-form-data`) schema describing the format of the response data.                             |  `true`  |\n| `bodySchema`  | A JSON schema that you can provide in case the conversion of the `body` Zod schema fails or produces an incorrect result in your OpenAPI spec. | `false`  |\n| `name`        | An optional name used in the generated OpenAPI spec for the response body, e.g. `GetTodosSuccessResponse`.                                     | `false`  |\n\nCalling the route operation outputs function allows you to chain your API handler logic with the [Route operation middleware](#route-operation-middleware) and [Route operation handler](#route-operation-handler) functions.\n\n##### [Route operation middleware](#route-operation-middleware)\n\nThe route operation middleware function is executed before validating the request input. The function takes in the same parameters as the Next.js [router handler](https://nextjs.org/docs/app/building-your-application/routing/route-handlers) (app router) and [API route](https://nextjs.org/docs/pages/building-your-application/routing/api-routes) (pages router) functions. Additionally, as a second parameter this function takes the return value of your last middleware function, defaulting to an empty object. Throwing an error inside a middleware function will stop the execution of the handler and you can also return a custom response like you would do within the [Route operation handler](#route-operation-handler) function. Calling the route operation middleware function allows you to chain your API handler logic with the [Route operation handler](#route-operation-handler) function. Alternatively, you may chain up to three middleware functions together:\n\n```typescript\n// App router.\nexport const { GET } = route({\n  getTodos: routeOperation({ method: 'GET' })\n    .middleware(() => {\n      return { foo: 'bar' };\n    })\n    .middleware((_req, _ctx, { foo }) => {\n      if (myCondition) {\n        return NextResponse.json({ error: 'My error.' }, { status: 400 });\n      }\n\n      return {\n        foo,\n        bar: 'baz'\n      };\n    })\n    .handler((_req, _ctx, { foo, bar }) => {\n      // ...\n    })\n});\n\n// Pages router.\nexport default apiRoute({\n  getTodos: routeOperation({ method: 'GET' })\n    .middleware(() => {\n      return { foo: 'bar' };\n    })\n    .middleware((req, res, { foo }) => {\n      if (myCondition) {\n        res.status(400).json({ error: 'My error.' });\n        return;\n      }\n\n      return {\n        foo,\n        bar: 'baz'\n      };\n    })\n    .handler((req, res, { foo, bar }) => {\n      // ...\n    })\n});\n```\n\n##### [Route operation handler](#route-operation-handler)\n\nThe route operation handler function is a strongly-typed function to implement the business logic for your API. The function takes in strongly-typed versions of the same parameters as the Next.js [router handler](https://nextjs.org/docs/app/building-your-application/routing/route-handlers) (app router) and [API route](https://nextjs.org/docs/pages/building-your-application/routing/api-routes) (pages router) functions. Additionally, as a third parameter this function takes the return value of your last middleware function (see above), defaulting to an empty object.\n\n### RPC\n\n#### [RPC route handler options](#rpc-route-handler-options)\n\nThe `rpcRouteHandler` (app router) and `rpcApiRouteHandler` (pages router) functions allow you to pass an object as the second parameter, where you can define a property called `openApiPath`. This property is an OpenAPI [Path Item Object](https://swagger.io/specification/#path-item-object) that can be used to override and extend the auto-generated specification for the given route.\n\n#### [RPC operations](#rpc-operations)\n\nThe `rpcOperation` function allows you to define your API handlers for your RPC endpoint. This function allows you to pass an OpenAPI [Operation object](https://swagger.io/specification/#operation-object) as a parameter, that can be used to override and extend the auto-generated specification for the given operation. Calling this function allows you to chain your API handler logic with the following functions.\n\n| Name         | Description                                                                                                                                                                                                                                                         |\n| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `input`      | An [RPC operation input](#rpc-operation-input) function for defining the validation and documentation of the operation.                                                                                                                                             |\n| `outputs`    | An [RPC operation outputs](#rpc-operation-outputs) function for defining the validation and documentation of the response.                                                                                                                                          |\n| `handler`    | An [RPC operation handler](#rpc-operation-handler) function for defining your business logic.                                                                                                                                                                       |\n| `middleware` | An [RPC operation middleware](#rpc-operation-middleware) function that gets executed before the operation input is validated. You may chain up to three middlewares together and share data between the middlewares by taking the input of the previous middleware. |\n\n##### [RPC operation input](#rpc-operation-input)\n\nThe RPC operation input function is used for type-checking, validation and documentation of the RPC call, taking in an object with the following properties:\n\n| Name          | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                            | Required |\n| ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- |\n| `contentType` | The content type header of the request, limited to `application/json`, `application/x-www-form-urlencoded` and `multipart/form-data`. When the content type is defined, a request with an incorrect content type header will get an error response.                                                                                                                                                                                                                    | `false`  |\n| `body`        | A [Zod](https://github.com/colinhacks/zod) schema describing the format of the request body. When using `application/x-www-form-urlencoded` or `multipart/form-data` content types, this should be a `zod-form-data` schema instead. When the body schema is defined, a request with an invalid request body will get an error response. The request body is parsed using this schema and updated to the request if valid, so the body should always match the schema. | `false`  |\n| `bodySchema`  | A JSON schema that you can provide in case the conversion of the `body` Zod schema fails or produces an incorrect result in your OpenAPI spec.                                                                                                                                                                                                                                                                                                                         | `false`  |\n\nCalling the RPC input function allows you to chain your API handler logic with the [RPC operation outputs](#rpc-operation-outputs), [RPC middleware](#rpc-operation-middleware) and [RPC handler](#rpc-operation-handler) functions.\n\n##### [RPC operation outputs](#rpc-operation-outputs)\n\nThe RPC operation outputs function is used for type-checking and documentation of the response, taking in an array of objects with the following properties:\n\n| Name         | Description                                                                                                                                    | Required |\n| ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------- | -------- |\n| `body`       | A [Zod](https://github.com/colinhacks/zod) (or `zod-form-data`) schema describing the format of the response data.                             |  `true`  |\n| `bodySchema` | A JSON schema that you can provide in case the conversion of the `body` Zod schema fails or produces an incorrect result in your OpenAPI spec. | `false`  |\n| `name`       | An optional name used in the generated OpenAPI spec for the response body, e.g. `GetTodosSuccessResponse`.                                     | `false`  |\n\nCalling the RPC operation outputs function allows you to chain your API handler logic with the [RPC operation middleware](#rpc-operation-middleware) and [RPC operation handler](#rpc-operation-handler) functions.\n\n##### [RPC operation middleware](#rpc-operation-middleware)\n\nThe RPC operation middleware function is executed before validating RPC operation input. The function takes in strongly typed parameters typed by the [RPC operation input](#rpc-operation-input) function. Additionally, as a second parameter this function takes the return value of your last middleware function, defaulting to an empty object. Throwing an error inside a middleware function will stop the execution of the handler. Calling the RPC operation middleware function allows you to chain your RPC API handler logic with the [RPC operation handler](#rpc-operation-handler) function. Alternatively, you may chain up to three middleware functions together:\n\n```typescript\n// App router.\nexport const { POST } = rpcRoute({\n  getTodos: rpcOperation()\n    .middleware(() => {\n      return { foo: 'bar' };\n    })\n    .middleware((_input, { foo }) => {\n      if (myCondition) {\n        throw Error('My error.');\n      }\n\n      return {\n        foo,\n        bar: 'baz'\n      };\n    })\n    .handler((_input, { foo, bar }) => {\n      // ...\n    })\n});\n\n// Pages router.\nexport default rpcApiRoute({\n  // ... Same as above.\n});\n```\n\n##### [RPC operation handler](#rpc-operation-handler)\n\nThe RPC operation handler function is a strongly-typed function to implement the business logic for your API. The function takes in strongly typed parameters typed by the [RPC operation input](#rpc-operation-input) function. Additionally, as a second parameter this function takes the return value of your last middleware function (see above), defaulting to an empty object.\n\n## [CLI](#cli)\n\nThe CLI commands will parse your Next.js APIs and generate/validate the `openapi.json` file.\nIf using TypeScript, you will need to install [tsx](https://github.com/privatenumber/tsx) and use it as the Node.js loader for the CLI commands below: `npm install --save-dev tsx`\n\n- `NODE_OPTIONS='--import=tsx' npx next-rest-framework generate` to generate the `openapi.json` file.\n- `NODE_OPTIONS='--import=tsx' npx next-rest-framework validate` to validate that the `openapi.json` file is up-to-date.\n\nThe `next-rest-framework validate` command is useful to have as part of the static checks in your CI/CD pipeline. Both commands support the following options:\n\n| Name                    | Description                                                                                                                                                                                    |\n| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `--configPath <string>` | In case you have multiple docs handlers with different configurations, you can specify which configuration you want to use by providing the path to the API. Example: `/api/my-configuration`. |\n\nA good practice is to set these in your `package.json` as both commands are needed:\n\n```json\n\"scripts\": {\n  \"generate\": \"NODE_OPTIONS='--import=tsx' next-rest-framework generate\",\n  \"validate\": \"NODE_OPTIONS='--import=tsx' next-rest-framework validate\",\n}\n```\n\n## [Changelog](#changelog)\n\nSee the changelog in [CHANGELOG.md](https://github.com/blomqma/next-rest-framework/blob/main/CHANGELOG.md)\n\n## [Contributing](#contributing)\n\nAll contributions are welcome!\n\n## [License](#license)\n\nISC, see full license in [LICENSE](https://github.com/blomqma/next-rest-framework/blob/main/LICENCE).\n","readmeFilename":"README.md","_rev":"1-b96099eca8b45eaafe66ec36009bf1b0"}