{"id":19391834,"url":"https://github.com/joeltg/next-rest","last_synced_at":"2025-04-24T00:31:54.321Z","repository":{"id":92290800,"uuid":"308907671","full_name":"joeltg/next-rest","owner":"joeltg","description":"Typesafe REST APIs for Next.js","archived":false,"fork":false,"pushed_at":"2023-03-19T00:54:27.000Z","size":4246,"stargazers_count":20,"open_issues_count":0,"forks_count":2,"subscribers_count":3,"default_branch":"main","last_synced_at":"2025-04-18T18:25:05.357Z","etag":null,"topics":["api","nextjs","rest","typescript"],"latest_commit_sha":null,"homepage":"","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/joeltg.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"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}},"created_at":"2020-10-31T15:06:42.000Z","updated_at":"2025-03-24T01:07:26.000Z","dependencies_parsed_at":"2023-05-22T17:31:12.526Z","dependency_job_id":null,"html_url":"https://github.com/joeltg/next-rest","commit_stats":{"total_commits":70,"total_committers":1,"mean_commits":70.0,"dds":0.0,"last_synced_commit":"e1b36f939cc3a65210f734a83adb4c0ea4881bc5"},"previous_names":[],"tags_count":13,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/joeltg%2Fnext-rest","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/joeltg%2Fnext-rest/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/joeltg%2Fnext-rest/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/joeltg%2Fnext-rest/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/joeltg","download_url":"https://codeload.github.com/joeltg/next-rest/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250539492,"owners_count":21447319,"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","nextjs","rest","typescript"],"created_at":"2024-11-10T10:29:22.247Z","updated_at":"2025-04-24T00:31:49.308Z","avatar_url":"https://github.com/joeltg.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# next-rest\n\n[![standard-readme compliant](https://img.shields.io/badge/readme%20style-standard-brightgreen.svg)](https://github.com/RichardLitt/standard-readme) [![license](https://img.shields.io/github/license/joeltg/next-rest)](https://opensource.org/licenses/MIT) [![NPM version](https://img.shields.io/npm/v/next-rest)](https://www.npmjs.com/package/next-rest) ![TypeScript types](https://img.shields.io/npm/types/next-rest)\n\nTypesafe REST APIs for Next.js.\n\n## Table of Contents\n\n- [Background](#background)\n- [Install](#install)\n- [Usage](#usage)\n  - [Defining runtime types](#defining-runtime-types)\n  - [Augmenting the API module](#augmenting-the-api-module)\n  - [Exporting the route handler](#exporting-the-route-handler)\n  - [Using the API client](#using-the-api-client)\n  - [Error handling](#error-handling)\n- [Contributing](#contributing)\n- [License](#license)\n\n## Background\n\nThis library is a framework for writing **end-to-end** typesafe JSON REST APIs for Next.js in TypeScript.\n\nFeatures:\n\n- **Modularity**. Instead of making you define all of your route types in one place, next-rest uses module augmentation so that you can declare each route's type in their own respective file. All of the logic for an API route `/api/foo/bar` is contained in the `/pages/api/foo/bar.ts` page.\n- **Minimalism**. The client API is 100 lines and just calls `fetch` like you'd expect. next-rest has one non-dev dependency on [http-status-codes](https://www.npmjs.com/package/http-status-codes). All validation happens on the server; using next-rest won't cause your validation library to get bundled into the client.\n- **Safety**: next-rest lets you write APIs where the URL parameters, request headers, request body, response headers, and response body are all (!!) strongly typed for each combination of route and method. All of your API calls get typechecked at compile-time by TypeScript _and_ validated at runtime on the server.\n\nLimitations:\n\n- **JSON-only**. next-rest is JSON-only.\n- **Internal use only**. next-rest is designed for implementing and calling REST APIs **within** a single Next.js application. You can't export your API types, or import a different project's API types. If _that's_ what you're after, you probably want something like [restyped](https://github.com/rawrmaan/restyped/).\n- Requires TypeScript 4.4+, Next.js 12+, and React 17+\n\n## Install\n\n```\nnpm i next-rest\n```\n\n## Usage\n\nThere are four basic steps. Most of the work happens inside the API route pages - once you've set those up right, you can just `import api from \"next-rest/client\"` from any client page or component and things will work like magic.\n\n### Defining runtime types\n\nnext-rest is designed to be used in conjunction with a validation library like [io-ts](https://github.com/gcanti/io-ts), [runtypes](https://github.com/pelotom/runtypes), or [zod](https://github.com/vriad/zod). Anything that supports a) static type inference and b) gives you [type predicates](https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards) for your types will work. The code samples here use io-ts.\n\nLet's write a route `/api/widgets/[id]` that supports `GET` and `DELETE` methods. The first thing we have to do is make io-ts codecs for our request headers and response bodies. For methods that don't accept content in the request body, we'll use `t.void`.\n\n```ts\n// pages/api/widget/[id].ts\n\nimport * as t from \"io-ts\"\n\nconst getRequestHeaders = t.type({ accept: t.literal(\"application/json\") })\nconst getRequestBody = t.void\n\nconst deleteRequestHeaders = t.type({ \"if-unmodified-since\": t.string })\nconst deleteRequestBody = t.void\n```\n\nThese serve as \"runtime representations\" of types. We also need type-level versions of those types, which we can get with the `t.TypeOf` utility type.\n\n```ts\n// pages/api/widget/[id].ts\n\ntype GetRequestHeaders = t.TypeOf\u003ctypeof getRequestHeaders\u003e\ntype GetRequestBody = t.TypeOf\u003ctypeof getRequestBody\u003e\ntype DeleteRequestHeaders = t.TypeOf\u003ctypeof deleteRequestHeaders\u003e\ntype DeleteRequestBody = t.TypeOf\u003ctypeof deleteRequestBody\u003e\n```\n\nLastly, we need types for our response headers and response bodies. These don't need to be validated at runtime (since it's the server that sends them), so we can just write them as normal TypeScript types.\n\n```ts\n// pages/api/widget/[id].ts\n\ntype GetResponseHeaders = {\n\t\"content-type\": \"application/json\"\n\t\"last-modified\": string\n}\n\ntype GetResponseBody = {\n\tid: string\n\tisGizmo: boolean\n}\n\ntype DeleteResponseHeaders = {}\n\ntype DeleteResponseBody = void\n```\n\n### Augmenting the API module\n\nThe central problem in designing a end-to-end typesafe API is finding a way to share types between server and client code without sharing anything else (ie without accidentally bundling actual server code into the client). We do this with next-rest by augmenting the `API` type in the `next-rest` module inside every API route page. These augmentations get merged and the client code in `next-rest/client` is able to access the merged API type by also importing `next-rest`.\n\n```ts\n// pages/api/widget/[id].ts\n\ndeclare module \"next-rest\" {\n\tinterface API {\n\t\t\"/api/widgets/[id]\": Route\u003c{\n\t\t\tGET: {\n\t\t\t\trequest: {\n\t\t\t\t\theaders: GetRequestHeaders\n\t\t\t\t\tbody: GetRequestBody\n\t\t\t\t}\n\t\t\t\tresponse: {\n\t\t\t\t\theaders: GetResponseHeaders\n\t\t\t\t\tbody: GetResponseBody\n\t\t\t\t}\n\t\t\t}\n\t\t\tDELETE: {\n\t\t\t\trequest: {\n\t\t\t\t\theaders: DeleteRequestHeaders\n\t\t\t\t\tbody: DeleteRequestBody\n\t\t\t\t}\n\t\t\t\tresponse: {\n\t\t\t\t\theaders: DeleteResponseHeaders\n\t\t\t\t\tbody: DeleteResponseBody\n\t\t\t\t}\n\t\t\t}\n\t\t}\u003e\n\t}\n}\n```\n\nNotice that the each entry is wrapped in a `Route\u003c...\u003e`. The `Route` type is just defined as `Route\u003cT extends MethodImplementation\u003e = T` and is just used to typecheck the method implementation. You don't have to `import` or `export` the `API` or `Route` types inside the `declare module \"next-rest\" { ... }` block; they're already in the module scope.\n\n### Exporting the route handler\n\nThe last thing to do in each server-side API route page is export the actual API handler. Next.js expects the default export to be a function `(req: NextApiRequest, res: NextApiResponse) =\u003e void` which we create by calling the `makeHandler` method exported frun `next-rest/server`.\n\n`makeHandler` takes a string API route as its first argument. The second argument is a configuration object that contains - for each method supported by the route - [custom type predicates](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) for the request headers and bodies, and an `exec` method implementing the actual handler for that method at that route.\n\nYou should be able to get custom type predicates from your runtime validation library. For io-ts, they're the `.is` property of the codec, like `getRequestHeaders.is: (value: unknown) =\u003e value is { accept: \"application/json\" })`.\n\nImplementing the exec method is where the magic starts kicking in: it takes a single `{ params, headers, body }` argument, but you don't have to declare any types. TypeScript knows to infer `params` from the route path parametrizing `makeHandler` (!!) and to infer `headers` and `body` from the augmented API module.\n\nThe exec method must return a Promise resolving to an object `{ headers, body }`. TypeScript will already know to expect the correct response headers and response body types and will complain if you don't provide them.\n\n```ts\n// pages/api/widget/[id].ts\n\nimport { makeHandler } from \"next-rest/server\"\n\nexport default makeHandler(\"/api/widgets/[id]\", {\n\tGET: {\n\t\theaders: getRequestHeaders.is,\n\t\tbody: getRequestBody.is,\n\t\texec: async ({ params, headers, body }) =\u003e {\n\t\t\t// TypeScript knows the types for all of these!\n\t\t\t// - var params: { id: string }\n\t\t\t// - var headers: { accept: \"application/json\" }\n\t\t\t// - var body: void\n\n\t\t\t// ... do implementation stuff\n\t\t\tconst { isGizmo, updatedAt } = await prisma.widgets.findUnique({\n\t\t\t\twhere: { id: params.id },\n\t\t\t\tselect: { isGizmo: true, updatedAt },\n\t\t\t})\n\n\t\t\treturn {\n\t\t\t\theaders: {\n\t\t\t\t\t\"content-type\": \"application/json\",\n\t\t\t\t\t\"last-modified\": new Date(updatedAt).toUTCString(),\n\t\t\t\t},\n\t\t\t\tbody: { id: params.id, isGizmo },\n\t\t\t}\n\t\t},\n\t},\n\tDELETE: {\n\t\theaders: deleteRequestHeaders.is,\n\t\tbody: deleteRequestBody.is,\n\t\texec: async ({ params, headers, body }) =\u003e {\n\t\t\t// TypeScript knows the types for all of these too!\n\t\t\t// - var params: { id: string }\n\t\t\t// - var headers: { \"if-unmodified-since\": string }\n\t\t\t// - var body: void\n\n\t\t\t// ... do implementation stuff\n\t\t\tconst updatedAt = new Date(headers[\"if-unmodified-since\"]).toISOString()\n\t\t\tconst { count } = await prisma.widgets.deleteMany({\n\t\t\t\twhere: { id: params.id, updatedAt: { lte: updatedAt } },\n\t\t\t})\n\t\t\treturn { headers: {}, body: undefined }\n\t\t},\n\t},\n})\n```\n\nPutting it all together, our complete sample API route page `pages/api/widget/[id].ts` looks like this:\n\n```ts\nimport * as t from \"io-ts\"\n\nimport { makeHandler } from \"next-rest/server\"\n\nconst getRequestHeaders = t.type({ accept: t.literal(\"application/json\") })\nconst getRequestBody = t.void\n\nconst deleteRequestHeaders = t.type({ \"if-unmodified-since\": t.string })\nconst deleteRequestBody = t.void\n\ntype GetRequestHeaders = t.TypeOf\u003ctypeof getRequestHeaders\u003e\ntype GetRequestBody = t.TypeOf\u003ctypeof getRequestBody\u003e\ntype GetResponseHeaders = {\n\t\"content-type\": \"application/json\"\n\t\"last-modified\": string\n}\ntype GetResponseBody = { id: string; isGizmo: boolean }\n\ntype DeleteRequestHeaders = t.TypeOf\u003ctypeof deleteRequestHeaders\u003e\ntype DeleteRequestBody = t.TypeOf\u003ctypeof deleteRequestBody\u003e\ntype DeleteResponseHeaders = {}\ntype DeleteResponseBody = void\n\ndeclare module \"next-rest\" {\n\tinterface API {\n\t\t\"/api/widgets/[id]\": Route\u003c{\n\t\t\tGET: {\n\t\t\t\trequest: {\n\t\t\t\t\theaders: GetRequestHeaders\n\t\t\t\t\tbody: GetRequestBody\n\t\t\t\t}\n\t\t\t\tresponse: {\n\t\t\t\t\theaders: GetResponseHeaders\n\t\t\t\t\tbody: GetResponseBody\n\t\t\t\t}\n\t\t\t}\n\t\t\tDELETE: {\n\t\t\t\trequest: {\n\t\t\t\t\theaders: DeleteRequestHeaders\n\t\t\t\t\tbody: DeleteRequestBody\n\t\t\t\t}\n\t\t\t\tresponse: {\n\t\t\t\t\theaders: DeleteResponseHeaders\n\t\t\t\t\tbody: DeleteResponseBody\n\t\t\t\t}\n\t\t\t}\n\t\t}\u003e\n\t}\n}\n\nexport default makeHandler(\"/api/widgets/[id]\", {\n\tGET: {\n\t\theaders: getRequestHeaders.is,\n\t\tbody: getRequestBody.is,\n\t\texec: async ({ params, headers, body }) =\u003e {\n\t\t\t// ... method implementation\n\t\t\treturn {\n\t\t\t\theaders: { \"content-type\": \"application/json\" },\n\t\t\t\tbody: { id: params.id, isGizmo: false },\n\t\t\t}\n\t\t},\n\t},\n\tDELETE: {\n\t\theaders: deleteRequestHeaders.is,\n\t\tbody: deleteRequestBody.is,\n\t\texec: async ({ params, headers, body }) =\u003e {\n\t\t\t// ... method implementation\n\t\t\treturn { headers: {}, body: undefined }\n\t\t},\n\t},\n})\n```\n\n### Using the API client\n\nNow that we've implemented our route on the server and augmented the `next-rest` module, we can start using the client API!\n\nThe client api is the default export of `next-rest/client`, and it's an object of functions for every HTTP method. This means you invoke the api like this:\n\n```ts\nimport api from \"next-rest/client\"\n\napi.get(\"/api/widgets/[id]\", { params: { id }, headers, body })\napi.delete(\"/api/widgets/[id]\", { params: { id }, headers, body })\n```\n\nThe first argument to the method function is the API route **without** any dynamic route parameters - e.g. `/api/widgets/[id]`, not `/api/widgets/81903281`. The second argument is an object with `params`, `headers`, and `body` properties. The `params` object is where you provide values for the dynamic route (`{ id: \"81903281\" }`).\n\nHere's an example component page at `components/widget.ts` that renders a widget and has a button that lets the user refresh the widget's `.isGizmo` property.\n\n```tsx\n// components/widget.ts\n\nimport React, { useCallback } from \"react\"\n\nimport api from \"next-rest/client\"\n\ninterface WidgetProps {\n\tid: string\n\tisGizmo: boolean\n}\n\nexport function Widget(props: WidgetProps) {\n\tconst [isGizmo, setIsGizmo] = useState\u003cboolean\u003e(props.isGizmo)\n\tconst [isChecking, setIsChecking] = useState(false)\n\n\tconst checkGizmoStatus = useCallback(() =\u003e {\n\t\tsetIsChecking(true)\n\t\tapi\n\t\t\t.get(\"/api/widgets/[id]\", {\n\t\t\t\tparams: { id: params.id },\n\t\t\t\theaders: { accept: \"application/json\" },\n\t\t\t\tbody: undefined,\n\t\t\t})\n\t\t\t.then(({ headers, body }) =\u003e {\n\t\t\t\t// TypeScript knows these types!\n\t\t\t\t// - var headers: { \"content-type\": \"application/json\" }\n\t\t\t\t// - var body: { id: string; isGizmo: boolean }\n\t\t\t\tsetIsGizmo(body.isGizmo)\n\t\t\t})\n\t\t\t.catch(() =\u003e alert(\"could not check gizmo status\"))\n\t\t\t.finally(() =\u003e setIsChecking(false))\n\t}, [])\n\n\treturn (\n\t\t\u003cdiv\u003e\n\t\t\t\u003cp\u003ei'm a widget!\u003c/p\u003e\n\t\t\t\u003cp\u003eand i {isGizmo ? \"am\" : \"am NOT\"} a gizmo\u003c/p\u003e\n\t\t\t\u003cinput\n\t\t\t\ttype=\"button\"\n\t\t\t\tonClick={checkGizmoStatus}\n\t\t\t\tdisabled={isChecking}\n\t\t\t\tvalue={isChecking ? \"checking...\" : \"check gizmo status\"}\n\t\t\t/\u003e\n\t\t\u003c/div\u003e\n\t)\n}\n```\n\nNotice the total lack of type annotation around the API call! In fact, as soon as you start typing `api.get`, you'll see something like this:\n\n![VSCode autocompleting the API routes that support GET requests](./images/Screen%20Recording%202021-11-04%20at%202.00.46%20PM.gif)\n\nTypeScript knows which API routes support GET requests - in this case there's just one - so it'll offer to autocomplete them for you. And once you select one, TypeScript will parametrize the rest of the API call with the types for that specific method:\n\n![VSCode autocompleting the route params, request headers, and request body](./images/Screen%20Recording%202021-11-04%20at%202.08.22%20PM.gif)\n\n... and when we get our result, TypeScript knows what's inside our response headers and body as well:\n\n![VSCode autocompleting the types of the response headers and response body](./images/Screen%20Recording%202021-11-04%20at%202.13.55%20PM.gif)\n\n### Error handling\n\nIf you throw an error from inside a method implementation on the server (ie inside one of your `exec` functions), next-rest will by default respond to the request with status code 500. If you want to control this, you can import `ServerError` from `next-rest/server` and throw one of those instead:\n\n```ts\ndeclare class ServerError extends Error {\n\treadonly status: number\n\tconstructor(status: number, message: string)\n}\n```\n\nFor example, we could modify our DELETE implementation to return a more informative status code in cases where the `if-unmodified-since` condition fails:\n\n```ts\n// pages/api/widget/[id].ts\n\nimport { StatusCodes } from \"http-status-codes\"\nimport { makeHandler, ServerError } from \"next-rest/server\"\n\nexport default makeHandler(\"/api/widgets/[id]\", {\n\t// ...\n\tDELETE: {\n\t\theaders: deleteRequestHeaders.is,\n\t\tbody: deleteRequestBody.is,\n\t\texec: async ({ params, headers, body }) =\u003e {\n\t\t\tconst updatedAt = new Date(headers[\"if-unmodified-since\"]).toISOString()\n\t\t\tconst { count } = await prisma.widgets.deleteMany({\n\t\t\t\twhere: { id: params.id, updatedAt: { lte: updatedAt } },\n\t\t\t})\n\n\t\t\tif (count === 0) {\n\t\t\t\t// This will cause next-rest to set the response status code to 412\n\t\t\t\tthrow new ServerError(\n\t\t\t\t\tStatusCodes.PRECONDITION_FAILED,\n\t\t\t\t\t\"you've got stale data, man!!\"\n\t\t\t\t)\n\t\t\t}\n\n\t\t\treturn { headers: {}, body: undefined }\n\t\t},\n\t},\n})\n```\n\nThere is a symmetric class `ClientError` exported from `next-rest/client` that we can use to handle this on the client as well.\n\n```ts\nclass ClientError extends Error {\n\treadonly status: number\n\tconstructor(status: number, message: string)\n}\n```\n\nIf the client receives any response other than 200, it will throw an instance of `ClientError` containing the status code and the response body as text.\n\n```ts\nimport { StatusCodes } from \"http-status-codes\"\nimport api, { ClientError } from \"next-rest/client\"\n\nfunction deleteWidget(id: string, updatedAt: string) {\n\tapi\n\t\t.delete(\"/api/widgets/[id]\", {\n\t\t\tparams: { id },\n\t\t\theaders: { \"if-unmodified-since\": new Date(updatedAt).toUTCString() },\n\t\t\tbody: undefined,\n\t\t})\n\t\t.then(({ headers, body }) =\u003e alert(\"widget deleted successfully\"))\n\t\t.catch((err) =\u003e {\n\t\t\tif (\n\t\t\t\terr instanceof ClientError \u0026\u0026\n\t\t\t\terr.status === StatusCodes.PRECONDITION_FAILED\n\t\t\t) {\n\t\t\t\tconsole.error(err.message) // \"you've got stale data, man!!\"\n\t\t\t\talert(\n\t\t\t\t\t\"could not delete widget because the request was made with stale data\"\n\t\t\t\t)\n\t\t\t} else {\n\t\t\t\talert(\"unknown error while deleting widget\")\n\t\t\t}\n\t\t})\n}\n```\n\n## Contributing\n\nIf you find a bug or have a suggestion, feel free to open an issue to discuss it!\n\n## License\n\nMIT © 2020 Joel Gustafson\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjoeltg%2Fnext-rest","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjoeltg%2Fnext-rest","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjoeltg%2Fnext-rest/lists"}