Package Exports
- @alan910127/next-api-builder
- @alan910127/next-api-builder/dist/index.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@alan910127/next-api-builder) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
Next.js REST API Builder
A simple, tRPC-like Next.js RESTful API builder based on Zod validation
Installation
Requirements
- Requirements of Zod
- TypeScript 4.5+
- Make sure you enabled
strictin yourtsconfig.json.
- Next.js
npm
npm install @alan910127/next-api-builderyarn
yarn add @alan910127/next-api-builderpnpm
pnpm add @alan910127/next-api-builderExample Usage
Create an endpoint in the [/src]/pages/api directory
// pages/api/hello.ts
import { randomUUID } from "crypto";
import { z } from "zod";
import { createEndpoint, procedure } from "@alan910127/next-api-builder";
export default createEndpoint({
get: procedure
.query(
z.object({
text: z.string().optional(),
})
)
.handler(async (req, res) => {
const text = req.query.text ?? "world";
// ^? (property): query: { text?: string | undefined; }
res.status(200).send(`Hello ${text}`);
}),
post: procedure
.body(
z.object({
name: z.string(),
age: z.number().nonnegative(),
})
)
.handler(async (req, res) => {
const { name, age } = req.body;
// ^? (property): body: { name: string; age: number; }
res.status(201).json({
id: randomUUID(),
name,
age,
});
}),
// ...put, delete etc.
});TODO
- Add support for multiple input validation schemas (For path parameters in dynamic routes or common input)
- Add support for middlewares