├── .eslintignore ├── .eslintrc.js ├── .github └── workflows │ └── ci.yml ├── .gitignore ├── .npmrc ├── .prettierignore ├── ARCHITECTURE.md ├── CHANGELOG.md ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENCE ├── README.md ├── apps └── example │ ├── .eslintrc.json │ ├── .gitignore │ ├── next.config.js │ ├── package.json │ ├── postcss.config.js │ ├── public │ └── openapi.json │ ├── src │ ├── actions.ts │ ├── app │ │ ├── (main) │ │ │ └── api │ │ │ │ └── v2 │ │ │ │ ├── form-data │ │ │ │ ├── multipart │ │ │ │ │ └── route.ts │ │ │ │ └── url-encoded │ │ │ │ │ └── route.ts │ │ │ │ ├── route-with-external-dep │ │ │ │ └── route.ts │ │ │ │ ├── route-with-params │ │ │ │ └── [slug] │ │ │ │ │ └── route.ts │ │ │ │ ├── route.ts │ │ │ │ ├── rpc │ │ │ │ └── [operationId] │ │ │ │ │ └── route.ts │ │ │ │ ├── third-party-endpoint │ │ │ │ └── route.ts │ │ │ │ └── todos │ │ │ │ ├── [id] │ │ │ │ └── route.ts │ │ │ │ └── route.ts │ │ ├── client │ │ │ ├── ClientExample.tsx │ │ │ └── page.tsx │ │ ├── components │ │ │ ├── Footer.tsx │ │ │ └── Navbar.tsx │ │ ├── favicon.ico │ │ ├── globals.css │ │ ├── layout.tsx │ │ └── page.tsx │ ├── pages │ │ └── api │ │ │ └── v1 │ │ │ ├── form-data │ │ │ ├── multipart │ │ │ │ └── index.ts │ │ │ └── url-encoded │ │ │ │ └── index.ts │ │ │ ├── index.ts │ │ │ ├── route-with-external-dep │ │ │ └── index.ts │ │ │ ├── route-with-params │ │ │ └── [slug] │ │ │ │ └── index.ts │ │ │ ├── rpc │ │ │ └── [operationId].ts │ │ │ ├── third-party-endpoint │ │ │ └── index.ts │ │ │ └── todos │ │ │ ├── [id].ts │ │ │ └── index.ts │ ├── scripts │ │ ├── custom-generate-openapi.ts │ │ └── custom-validate-openapi.ts │ └── utils.ts │ ├── tailwind.config.ts │ └── tsconfig.json ├── docs ├── babel.config.js ├── blog │ ├── 2022-12-14-announcing-next-rest-framework.md │ └── authors.yml ├── docs │ ├── api-reference.md │ ├── getting-started.md │ └── intro.md ├── docusaurus.config.js ├── package.json ├── sidebars.js ├── src │ ├── components │ │ └── HomepageFeatures │ │ │ ├── index.tsx │ │ │ └── styles.module.css │ ├── css │ │ └── custom.css │ └── pages │ │ ├── index.module.css │ │ └── index.tsx ├── static │ ├── .nojekyll │ ├── high-level-architecture │ ├── high-level-architecture.svg │ ├── img │ │ ├── docs-screenshot.jpg │ │ ├── easy-to-use.svg │ │ ├── extendable.svg │ │ ├── favicon.ico │ │ ├── lightweight.svg │ │ ├── logo.svg │ │ ├── reuse.svg │ │ ├── self-documenting.svg │ │ └── type-safe.svg │ └── next-rest-framework-demo.gif └── tsconfig.json ├── package.json ├── packages └── next-rest-framework │ ├── .eslintrc.js │ ├── LICENCE │ ├── README.md │ ├── favicon.ico │ ├── jest.config.ts │ ├── logo.svg │ ├── package.json │ ├── src │ ├── app-router │ │ ├── docs-route.ts │ │ ├── index.ts │ │ ├── route-operation.ts │ │ ├── route.ts │ │ └── rpc-route.ts │ ├── cli │ │ ├── constants.ts │ │ ├── generate.ts │ │ ├── index.ts │ │ ├── utils.ts │ │ └── validate.ts │ ├── client │ │ ├── index.ts │ │ └── rpc-client.ts │ ├── constants.ts │ ├── global.d.ts │ ├── index.ts │ ├── pages-router │ │ ├── api-route-operation.ts │ │ ├── api-route.ts │ │ ├── docs-api-route.ts │ │ ├── index.ts │ │ └── rpc-api-route.ts │ ├── shared │ │ ├── config.ts │ │ ├── docs.ts │ │ ├── form-data.ts │ │ ├── index.ts │ │ ├── logging.ts │ │ ├── paths.ts │ │ ├── rpc-operation.ts │ │ ├── schemas.ts │ │ └── utils.ts │ └── types.ts │ ├── tests │ ├── app-router │ │ ├── docs-route.test.ts │ │ ├── route.test.ts │ │ └── rpc-route.test.ts │ ├── pages-router │ │ ├── api-route.test.ts │ │ ├── docs-api-route.test.ts │ │ └── rpc-api-route.test.ts │ └── utils.ts │ ├── tsconfig.json │ └── tsup.config.ts ├── pnpm-lock.yaml └── pnpm-workspace.yaml /.eslintignore: -------------------------------------------------------------------------------- 1 | dist 2 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | 3 | module.exports = { 4 | root: true, 5 | extends: ['standard-with-typescript', 'prettier'], 6 | parserOptions: { 7 | project: [ 8 | path.resolve(__dirname, './packages/*/tsconfig.json'), 9 | path.resolve(__dirname, './apps/*/tsconfig.json'), 10 | path.resolve(__dirname, './docs/tsconfig.json') 11 | ] 12 | }, 13 | rules: { 14 | '@typescript-eslint/strict-boolean-expressions': 'off', 15 | '@typescript-eslint/explicit-function-return-type': 'off', 16 | '@typescript-eslint/restrict-template-expressions': 'off' 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: "CI" 2 | 3 | on: 4 | push: 5 | branches: 6 | - "**" 7 | 8 | jobs: 9 | build: 10 | name: "Run CI pipeline" 11 | runs-on: ubuntu-latest 12 | strategy: 13 | matrix: 14 | node: [18, 20] 15 | steps: 16 | - uses: actions/checkout@v3 17 | - uses: pnpm/action-setup@v2 18 | with: 19 | version: 7 20 | - uses: actions/setup-node@v3 21 | with: 22 | node-version: ${{ matrix.node }} 23 | cache: "pnpm" 24 | - run: pnpm i --frozen-lockfile 25 | - run: pnpm run ci 26 | 27 | - name: Coverage 28 | uses: codecov/codecov-action@v3 29 | with: 30 | fail_ci_if_error: false 31 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | coverage 3 | dist 4 | tsconfig.tsbuildinfo 5 | .next 6 | next-env.d.ts 7 | build 8 | .docusaurus 9 | -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | auto-install-peers=true 2 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | dist 2 | .next 3 | coverage 4 | .docusaurus 5 | -------------------------------------------------------------------------------- /ARCHITECTURE.md: -------------------------------------------------------------------------------- 1 | # Architecture 2 | 3 | Next REST Framework is heavily tied to the Next.js APIs and the high-level architecture of the framework consists of two main parts, the CLI and the public API used in runtime execution: 4 | 5 | ![High-level architecture](./docs/static/high-level-architecture.svg) 6 | 7 | ## Public API 8 | 9 | The public API of Next REST Framework contains all of the functions you need to use the framework and build your APIs. These are the entry points that handle the request validation and they also provide internal methods for generating the open API spec for the given single endpoint, used by the CLI. 10 | 11 | ## CLI 12 | 13 | The CLI contains most of the logic when it comes to actually building the OpenAPI spec from your APIs and generating the `openapi.json` file. Note that generating the OpenAPI spec and exposing a public documentation are completely optional and Next REST Framework can be used without them for it's type-safety features. 14 | 15 | For the CLI to be able to generate the OpenAPI spec, it needs to parse and read your code that is built using the methods from the public API. This process includes an intermediate step of bundling the relevant code to a common format regardless of the environment the CLI is run. For this, ESBuild is used to generate a temporary bundle of a subset of the application in a folder called `.next-rest-framework`. This build output is then analyzed by the CLI and the Zod schemas are parsed from each endpoint and included to a single output written in the `openapi.json` file. 16 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, caste, color, religion, or sexual 10 | identity and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | - Demonstrating empathy and kindness toward other people 21 | - Being respectful of differing opinions, viewpoints, and experiences 22 | - Giving and gracefully accepting constructive feedback 23 | - Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | - Focusing on what is best not just for us as individuals, but for the overall 26 | community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | - The use of sexualized language or imagery, and sexual attention or advances of 31 | any kind 32 | - Trolling, insulting or derogatory comments, and personal or political attacks 33 | - Public or private harassment 34 | - Publishing others' private information, such as a physical or email address, 35 | without their explicit permission 36 | - Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | blomqma@omg.lol. 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series of 86 | actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or permanent 93 | ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within the 113 | community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.1, available at 119 | [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. 120 | 121 | Community Impact Guidelines were inspired by 122 | [Mozilla's code of conduct enforcement ladder][mozilla coc]. 123 | 124 | For answers to common questions about this code of conduct, see the FAQ at 125 | [https://www.contributor-covenant.org/faq][faq]. Translations are available at 126 | [https://www.contributor-covenant.org/translations][translations]. 127 | 128 | [homepage]: https://www.contributor-covenant.org 129 | [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html 130 | [mozilla coc]: https://github.com/mozilla/diversity 131 | [faq]: https://www.contributor-covenant.org/faq 132 | [translations]: https://www.contributor-covenant.org/translations 133 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Development 2 | 3 | Clone the repository: 4 | 5 | ``` 6 | git clone git@github.com:blomqma/next-rest-framework.git 7 | ``` 8 | 9 | Install dependencies: 10 | 11 | ``` 12 | pnpm i 13 | ``` 14 | 15 | Build the `next-rest-framework` package: 16 | 17 | ``` 18 | pnpm run build 19 | ``` 20 | 21 | Run the development Next.js project: 22 | 23 | ``` 24 | pnpm run dev 25 | ``` 26 | 27 | To test your changes in the `next-rest-framework` package against the dev project, simply rebuild the package with `pnpm run build` and the changes will be synced automatically. 28 | 29 | Run unit tests: 30 | 31 | ``` 32 | pnpm run test 33 | ``` 34 | 35 | Run unit tests in watch mode: 36 | 37 | ``` 38 | pnpm run test:watch 39 | ``` 40 | 41 | Run formatting: 42 | 43 | ``` 44 | pnpm run format 45 | ``` 46 | 47 | Run linting: 48 | 49 | ``` 50 | pnpm run lint 51 | ``` 52 | 53 | # Documentation 54 | 55 | All documentation is in [README.md](https://github.com/blomqma/next-rest-framework/blob/main/README.md), please update that when needed. 56 | 57 | # Pull requests 58 | 59 | All pull requests are welcome and done against the `main` branch, please write tests for all changes, write documentation when needed and use descriptive commit messages. No need to update the changelog. 60 | 61 | # License 62 | 63 | By contributing, you agree to license your contribution under the [LICENSE](https://github.com/blomqma/next-rest-framework/blob/main/LICENCE). 64 | -------------------------------------------------------------------------------- /LICENCE: -------------------------------------------------------------------------------- 1 | packages/next-rest-framework/LICENCE -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | packages/next-rest-framework/README.md -------------------------------------------------------------------------------- /apps/example/.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "next/core-web-vitals", 3 | "rules": { 4 | "@typescript-eslint/triple-slash-reference": "off", 5 | "@next/next/no-html-link-for-pages": ["error", "./apps/example/src/app"] // When linting from the root of the monorepo. 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /apps/example/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | .yarn/install-state.gz 8 | 9 | # testing 10 | /coverage 11 | 12 | # next.js 13 | /.next/ 14 | /out/ 15 | 16 | # production 17 | /build 18 | 19 | # misc 20 | .DS_Store 21 | *.pem 22 | 23 | # debug 24 | npm-debug.log* 25 | yarn-debug.log* 26 | yarn-error.log* 27 | 28 | # local env files 29 | .env*.local 30 | 31 | # vercel 32 | .vercel 33 | 34 | # typescript 35 | *.tsbuildinfo 36 | next-env.d.ts 37 | -------------------------------------------------------------------------------- /apps/example/next.config.js: -------------------------------------------------------------------------------- 1 | /** @type {import('next').NextConfig} */ 2 | const nextConfig = {} 3 | 4 | module.exports = nextConfig 5 | -------------------------------------------------------------------------------- /apps/example/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "example", 3 | "private": true, 4 | "scripts": { 5 | "prebuild": "cd ../.. && pnpm build && cd apps/example", 6 | "dev": "pnpm prebuild && next dev", 7 | "build": "pnpm prebuild && next build", 8 | "start": "next start", 9 | "generate": "pnpm prebuild && NODE_OPTIONS='--import=tsx' next-rest-framework generate", 10 | "validate": "pnpm prebuild && NODE_OPTIONS='--import=tsx' next-rest-framework validate", 11 | "custom-generate-openapi": "pnpm prebuild && tsx ./src/scripts/custom-generate-openapi.ts", 12 | "custom-validate-openapi": "pnpm prebuild && tsx ./src/scripts/custom-validate-openapi.ts", 13 | "lint": "tsc && next lint" 14 | }, 15 | "dependencies": { 16 | "jsdom": "24.0.0", 17 | "next-rest-framework": "workspace:*", 18 | "tsx": "4.7.2", 19 | "zod-form-data": "2.0.2" 20 | }, 21 | "devDependencies": { 22 | "@types/jsdom": "^21.1.6", 23 | "autoprefixer": "10.0.1", 24 | "eslint-config-next": "14.0.4", 25 | "postcss": "8.4.33", 26 | "tailwindcss": "3.3.0" 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /apps/example/postcss.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | plugins: { 3 | tailwindcss: {}, 4 | autoprefixer: {}, 5 | }, 6 | } 7 | -------------------------------------------------------------------------------- /apps/example/src/actions.ts: -------------------------------------------------------------------------------- 1 | 'use server'; 2 | 3 | import { rpcOperation } from 'next-rest-framework'; 4 | import { 5 | MOCK_TODOS, 6 | formSchema, 7 | multipartFormSchema, 8 | todoSchema 9 | } from '@/utils'; 10 | import { z } from 'zod'; 11 | 12 | // The RPC operations can be used as server-actions and imported in the RPC route handlers. 13 | 14 | export const getTodos = rpcOperation() 15 | .outputs([ 16 | { 17 | body: z.array(todoSchema).describe('List of TODOs.'), 18 | contentType: 'application/json' 19 | } 20 | ]) 21 | .handler(() => { 22 | return MOCK_TODOS; 23 | }); 24 | 25 | export const getTodoById = rpcOperation() 26 | .input({ 27 | contentType: 'application/json', 28 | body: z.string().describe('TODO name.') 29 | }) 30 | .outputs([ 31 | { 32 | body: z 33 | .object({ 34 | error: z.string() 35 | }) 36 | .describe('TODO not found.'), 37 | contentType: 'application/json' 38 | }, 39 | { 40 | body: todoSchema.describe('TODO response.'), 41 | contentType: 'application/json' 42 | } 43 | ]) 44 | .handler((id) => { 45 | const todo = MOCK_TODOS.find((t) => t.id === Number(id)); 46 | 47 | if (!todo) { 48 | return { error: 'TODO not found.' }; 49 | } 50 | 51 | return todo; 52 | }); 53 | 54 | export const createTodo = rpcOperation() 55 | .input({ 56 | contentType: 'application/json', 57 | body: z 58 | .object({ 59 | name: z.string() 60 | }) 61 | .describe("New TODO's name.") 62 | }) 63 | .outputs([{ body: todoSchema, contentType: 'application/json' }]) 64 | .handler(async ({ name }) => { 65 | const todo = { id: 4, name, completed: false }; 66 | return todo; 67 | }); 68 | 69 | export const deleteTodo = rpcOperation() 70 | .input({ 71 | contentType: 'application/json', 72 | body: z.string() 73 | }) 74 | .outputs([ 75 | { 76 | body: z.object({ error: z.string() }).describe('TODO not found.'), 77 | contentType: 'application/json' 78 | }, 79 | { 80 | body: z.object({ message: z.string() }).describe('TODO deleted message.'), 81 | contentType: 'application/json' 82 | } 83 | ]) 84 | .handler((id) => { 85 | const todo = MOCK_TODOS.find((t) => t.id === Number(id)); 86 | 87 | if (!todo) { 88 | return { 89 | error: 'TODO not found.' 90 | }; 91 | } 92 | 93 | return { message: 'TODO deleted.' }; 94 | }); 95 | 96 | export const formDataUrlEncoded = rpcOperation() 97 | .input({ 98 | contentType: 'application/x-www-form-urlencoded', 99 | body: formSchema.describe('Test form description.') // A zod-form-data schema is required. 100 | }) 101 | .outputs([ 102 | { 103 | body: formSchema.describe('Test form response.'), 104 | contentType: 'application/json' 105 | } 106 | ]) 107 | .handler((formData) => { 108 | return { 109 | text: formData.get('text') 110 | }; 111 | }); 112 | 113 | export const formDataMultipart = rpcOperation() 114 | .input({ 115 | contentType: 'multipart/form-data', 116 | body: multipartFormSchema, // A zod-form-data schema is required. 117 | // The binary file cannot described with a Zod schema so we define it by hand for the OpenAPI spec. 118 | bodySchema: { 119 | description: 'Test form description.', 120 | type: 'object', 121 | properties: { 122 | text: { 123 | type: 'string' 124 | }, 125 | file: { 126 | type: 'string', 127 | format: 'binary' 128 | } 129 | } 130 | } 131 | }) 132 | .outputs([ 133 | { 134 | body: z.custom(), 135 | // The binary file cannot described with a Zod schema so we define it by hand for the OpenAPI spec. 136 | bodySchema: { 137 | description: 'File response.', 138 | type: 'string', 139 | format: 'binary' 140 | }, 141 | contentType: 'application/json' 142 | } 143 | ]) 144 | .handler((formData) => { 145 | const file = formData.get('file'); 146 | return file; 147 | }); 148 | -------------------------------------------------------------------------------- /apps/example/src/app/(main)/api/v2/form-data/multipart/route.ts: -------------------------------------------------------------------------------- 1 | import { TypedNextResponse, route, routeOperation } from 'next-rest-framework'; 2 | import { multipartFormSchema } from '@/utils'; 3 | import { z } from 'zod'; 4 | 5 | export const runtime = 'edge'; 6 | 7 | export const { POST } = route({ 8 | multipartFormData: routeOperation({ 9 | method: 'POST' 10 | }) 11 | .input({ 12 | contentType: 'multipart/form-data', 13 | body: multipartFormSchema, // A zod-form-data schema is required. 14 | // The binary file cannot described with a Zod schema so we define it by hand for the OpenAPI spec. 15 | bodySchema: { 16 | description: 'Test form description.', 17 | type: 'object', 18 | properties: { 19 | text: { 20 | type: 'string' 21 | }, 22 | file: { 23 | type: 'string', 24 | format: 'binary' 25 | } 26 | } 27 | } 28 | }) 29 | .outputs([ 30 | { 31 | status: 200, 32 | contentType: 'application/octet-stream', 33 | body: z.custom(), 34 | // The binary file cannot described with a Zod schema so we define it by hand for the OpenAPI spec. 35 | bodySchema: { 36 | description: 'File response.', 37 | type: 'string', 38 | format: 'binary' 39 | } 40 | } 41 | ]) 42 | .handler(async (req) => { 43 | // const json = await req.json(); // Form can also be parsed as JSON. 44 | const formData = await req.formData(); 45 | const file = formData.get('file'); 46 | 47 | return new TypedNextResponse(file, { 48 | status: 200, 49 | headers: { 50 | 'Content-Type': 'application/octet-stream', 51 | 'Content-Disposition': `attachment; filename="${file.name}"` 52 | } 53 | }); 54 | }) 55 | }); 56 | -------------------------------------------------------------------------------- /apps/example/src/app/(main)/api/v2/form-data/url-encoded/route.ts: -------------------------------------------------------------------------------- 1 | import { formSchema } from '@/utils'; 2 | import { TypedNextResponse, route, routeOperation } from 'next-rest-framework'; 3 | 4 | export const runtime = 'edge'; 5 | 6 | export const { POST } = route({ 7 | urlEncodedFormData: routeOperation({ 8 | method: 'POST' 9 | }) 10 | .input({ 11 | contentType: 'application/x-www-form-urlencoded', 12 | body: formSchema.describe('Test form description.') // A zod-form-data schema is required. 13 | }) 14 | .outputs([ 15 | { 16 | status: 200, 17 | contentType: 'application/octet-stream', 18 | body: formSchema.describe('Test form response.') // A zod-form-data schema is required. 19 | } 20 | ]) 21 | .handler(async (req) => { 22 | const { text } = await req.json(); 23 | // const formData = await req.formData(); // Form can also be parsed as form data. 24 | 25 | // Type-checked response. 26 | return TypedNextResponse.json({ 27 | text 28 | }); 29 | }) 30 | }); 31 | -------------------------------------------------------------------------------- /apps/example/src/app/(main)/api/v2/route-with-external-dep/route.ts: -------------------------------------------------------------------------------- 1 | import { TypedNextResponse, route, routeOperation } from 'next-rest-framework'; 2 | import { JSDOM } from 'jsdom'; 3 | import { z } from 'zod'; 4 | 5 | export const { GET } = route({ 6 | routeWithExternalDep: routeOperation({ 7 | method: 'GET' 8 | }) 9 | .outputs([ 10 | { 11 | contentType: 'text/html', 12 | status: 200, 13 | body: z.string() 14 | } 15 | ]) 16 | .handler(() => { 17 | const dom = new JSDOM('

Hello world

'); 18 | 19 | return new TypedNextResponse(dom.serialize(), { 20 | headers: { 'Content-Type': 'text/html' } 21 | }); 22 | }) 23 | }); 24 | -------------------------------------------------------------------------------- /apps/example/src/app/(main)/api/v2/route-with-params/[slug]/route.ts: -------------------------------------------------------------------------------- 1 | import { TypedNextResponse, route, routeOperation } from 'next-rest-framework'; 2 | import { z } from 'zod'; 3 | 4 | const paramsSchema = z.object({ 5 | slug: z.enum(['foo', 'bar', 'baz']) 6 | }); 7 | 8 | const querySchema = z.object({ 9 | total: z.string() 10 | }); 11 | 12 | export const runtime = 'edge'; 13 | 14 | export const { GET } = route({ 15 | getPathParams: routeOperation({ 16 | method: 'GET' 17 | }) 18 | .input({ 19 | contentType: 'application/json', 20 | params: paramsSchema.describe('Path parameters input.'), 21 | query: querySchema.describe('Query parameters input.') 22 | }) 23 | .outputs([ 24 | { 25 | status: 200, 26 | contentType: 'application/json', 27 | body: paramsSchema.merge(querySchema).describe('Parameters response.') 28 | } 29 | ]) 30 | .handler((req, { params: { slug } }) => { 31 | const query = req.nextUrl.searchParams; 32 | 33 | return TypedNextResponse.json({ 34 | slug, 35 | total: query.get('total') ?? '' 36 | }); 37 | }) 38 | }); 39 | -------------------------------------------------------------------------------- /apps/example/src/app/(main)/api/v2/route.ts: -------------------------------------------------------------------------------- 1 | import { docsRoute } from 'next-rest-framework'; 2 | 3 | export const runtime = 'edge'; 4 | 5 | export const { GET } = docsRoute({ 6 | deniedPaths: ['/api/v2/third-party-endpoint', '/api/v1/third-party-endpoint'] 7 | }); 8 | -------------------------------------------------------------------------------- /apps/example/src/app/(main)/api/v2/rpc/[operationId]/route.ts: -------------------------------------------------------------------------------- 1 | import { 2 | createTodo, 3 | deleteTodo, 4 | getTodoById, 5 | getTodos, 6 | formDataUrlEncoded, 7 | formDataMultipart 8 | } from '@/actions'; 9 | import { rpcRoute } from 'next-rest-framework'; 10 | 11 | export const runtime = 'edge'; 12 | 13 | export const { POST } = rpcRoute({ 14 | getTodos, 15 | getTodoById, 16 | createTodo, 17 | deleteTodo, 18 | formDataUrlEncoded, 19 | formDataMultipart 20 | }); 21 | 22 | export type RpcClient = typeof POST.client; 23 | -------------------------------------------------------------------------------- /apps/example/src/app/(main)/api/v2/third-party-endpoint/route.ts: -------------------------------------------------------------------------------- 1 | import { NextResponse } from 'next/server'; 2 | 3 | export const runtime = 'edge'; 4 | 5 | // You can still write regular routes with Next REST Framework. 6 | export const GET = () => { 7 | return NextResponse.json('Hello World!', { 8 | headers: { 'Content-Type': 'text/plain' } 9 | }); 10 | }; 11 | -------------------------------------------------------------------------------- /apps/example/src/app/(main)/api/v2/todos/[id]/route.ts: -------------------------------------------------------------------------------- 1 | import { MOCK_TODOS, todoSchema } from '@/utils'; 2 | import { TypedNextResponse, route, routeOperation } from 'next-rest-framework'; 3 | import { z } from 'zod'; 4 | 5 | export const runtime = 'edge'; 6 | 7 | const paramsSchema = z 8 | .object({ 9 | id: z.string() 10 | }) 11 | .describe('TODO ID path parameter.'); 12 | 13 | export const { GET, DELETE } = route({ 14 | getTodoById: routeOperation({ 15 | method: 'GET' 16 | }) 17 | .input({ 18 | params: paramsSchema 19 | }) 20 | .outputs([ 21 | { 22 | body: todoSchema.describe('TODO response.'), 23 | status: 200, 24 | contentType: 'application/json' 25 | }, 26 | { 27 | body: z.string().describe('TODO not found.'), 28 | status: 404, 29 | contentType: 'application/json' 30 | } 31 | ]) 32 | .handler((_req, { params: { id } }) => { 33 | const todo = MOCK_TODOS.find((t) => t.id === Number(id)); 34 | 35 | if (!todo) { 36 | return TypedNextResponse.json('TODO not found.', { 37 | status: 404 38 | }); 39 | } 40 | 41 | return TypedNextResponse.json(todo, { 42 | status: 200 43 | }); 44 | }), 45 | 46 | deleteTodo: routeOperation({ 47 | method: 'DELETE' 48 | }) 49 | .input({ 50 | params: paramsSchema 51 | }) 52 | .outputs([ 53 | { 54 | body: z.string().describe('TODO deleted.'), 55 | status: 204, 56 | contentType: 'application/json' 57 | }, 58 | { 59 | body: z.string().describe('TODO not found.'), 60 | status: 404, 61 | contentType: 'application/json' 62 | } 63 | ]) 64 | .handler((_req, { params: { id } }) => { 65 | const todo = MOCK_TODOS.find((t) => t.id === Number(id)); 66 | 67 | if (!todo) { 68 | return TypedNextResponse.json('TODO not found.', { 69 | status: 404 70 | }); 71 | } 72 | 73 | // Delete todo. 74 | 75 | return TypedNextResponse.json('TODO deleted.', { 76 | status: 204 77 | }); 78 | }) 79 | }); 80 | -------------------------------------------------------------------------------- /apps/example/src/app/(main)/api/v2/todos/route.ts: -------------------------------------------------------------------------------- 1 | import { TypedNextResponse, route, routeOperation } from 'next-rest-framework'; 2 | import { MOCK_TODOS, todoSchema } from '@/utils'; 3 | import { z } from 'zod'; 4 | 5 | export const runtime = 'edge'; 6 | 7 | export const { GET, POST } = route({ 8 | getTodos: routeOperation({ 9 | method: 'GET' 10 | }) 11 | .outputs([ 12 | { 13 | status: 200, 14 | contentType: 'application/json', 15 | body: z.array(todoSchema).describe('List of TODOs.') 16 | } 17 | ]) 18 | .handler(() => { 19 | return TypedNextResponse.json(MOCK_TODOS, { 20 | status: 200 21 | }); 22 | }), 23 | 24 | createTodo: routeOperation({ 25 | method: 'POST' 26 | }) 27 | .input({ 28 | contentType: 'application/json', 29 | body: z 30 | .object({ 31 | name: z.string() 32 | }) 33 | .describe("New TODO's name.") 34 | }) 35 | .outputs([ 36 | { 37 | status: 201, 38 | contentType: 'application/json', 39 | body: z.string().describe('New TODO created message.') 40 | }, 41 | { 42 | status: 401, 43 | contentType: 'application/json', 44 | body: z.string().describe('Unauthorized.') 45 | } 46 | ]) 47 | // Optional middleware logic executed before request validation. 48 | .middleware((req) => { 49 | if (!req.headers.get('very-secure')) { 50 | return TypedNextResponse.json('Unauthorized.', { 51 | status: 401 52 | }); 53 | } 54 | }) 55 | .handler(async (req) => { 56 | const { name } = await req.json(); 57 | 58 | return TypedNextResponse.json(`New TODO created: ${name}`, { 59 | status: 201 60 | }); 61 | }) 62 | }); 63 | -------------------------------------------------------------------------------- /apps/example/src/app/client/ClientExample.tsx: -------------------------------------------------------------------------------- 1 | 'use client'; 2 | 3 | import { rpcClient } from 'next-rest-framework/dist/client'; 4 | import { useEffect, useState } from 'react'; 5 | import { type Todo } from '@/utils'; 6 | import { type RpcClient } from '../(main)/api/v2/rpc/[operationId]/route'; 7 | 8 | const client = rpcClient({ 9 | url: 'http://localhost:3000/api/v2/rpc' 10 | }); 11 | 12 | export const ClientExample: React.FC = () => { 13 | const [loading, setLoading] = useState(true); 14 | const [todos, setTodos] = useState([]); 15 | 16 | useEffect(() => { 17 | client 18 | .getTodos() 19 | .then(setTodos) 20 | .catch(console.error) 21 | .finally(() => { 22 | setLoading(false); 23 | }); 24 | }, []); 25 | 26 | return ( 27 |
28 |

RPC client example

29 | {loading ? ( 30 |

Loading...

31 | ) : ( 32 | <> 33 |

Data:

{JSON.stringify(todos)}

34 | 35 | )} 36 |
37 | ); 38 | }; 39 | -------------------------------------------------------------------------------- /apps/example/src/app/client/page.tsx: -------------------------------------------------------------------------------- 1 | import { getTodos } from '@/actions'; 2 | import { Footer } from '@/app/components/Footer'; 3 | import { Navbar } from '@/app/components/Navbar'; 4 | import { ClientExample } from '@/app/client/ClientExample'; 5 | 6 | export default async function Page() { 7 | const todos = await getTodos(); 8 | 9 | return ( 10 | <> 11 | 12 |
13 |
14 |

RPC server-side client example

15 |

Data:

16 |

{JSON.stringify(todos)}

17 |
18 | 19 |
20 |