next-typed-api-routes
Write a Schema
interface in your API route file, and you get
- route parameters validation and type completion
- typed API clients
- faster JSON response serialization
all at one command!
Requirement for the target Next.js Project
- Use TypeScript
- Set
"baseUrl": "."
in tsconfig.json
compilerOptions
part
{
"compilerOptions": {
"baseUrl": "."
}
}
- All codes should live in
src
dir next.js src directory
Get Started
- Install the package in your Next.js TypeScript project
npm install --save @ddadaal/next-typed-api-routes
- Create a API route
src/pages/api/test.ts
with the following content
import { route } from "@ddadaal/next-typed-api-routes";
interface Value {
articleId: number;
}
export interface TestApiSchema {
method: "POST";
query: {
a?: string | number;
};
body: {
test: string;
};
responses: {
200: { test: string; }
403: { message: string; }
}
}
export default route<TestApiSchema>("TestApiSchema", async (req) => {
const { a } = req.query;
const { test } = req.body;
return { 200: { test: test + "" + a } };
});
- Run
npx ntar schema && npx ntar client
schemas.json
will be generated at the module folder under node_modules
. You should never edit it directly. The project cannot start without this file.
src/apis/api.ts
will be generated at src/apis
.
- Import the
api
variable from src/apis/api.ts
to use the client.
import { api } from "src/apis/api";
api.testApi({ query: {}, body: { test: "123" } })
.httpError(403, ({ message }) => { console.log(403, message); })
.then(({ test }) => { console.log(test); });
- Important Add
ntar schema
to postinstall
script in your package.json
so that schemas.json
will be generated every time your project is npm install
ed.
{
"scripts": {
"postinstall": "ntar schema"
}
}
Updating existing API Routes
To convert a normal API Routes to a type checked one, all you need to do is
- Write a valid
Schema
interface - Wrap the handler function with
route
function, specify the name of Schema interface as the type argument and first argument
The Get Started part provides an example of a correctly formatted API route file. ntar
will report errors if Incorrect route file is found.
Run ntar schema
when the Schema
interface is changed.
Run ntar client
when the HTTP method or URL or the name of schema is changed.
Schema Interface Specification
The shape of Schema interface is defined as follows:
interface TestSchema {
method: "POST";
query: {
property?: string | number | AnotherInterface | Pick<{ number: string }, "number">;
anotherProperty: string;
}
body: {
property?: string | number | AnotherInterface | Pick<{ number: string }, "number">;
}
responses: {
200: {
property?: string | number | AnotherInterface | Pick<{ number: string }, "number">;
};
404: null;
}
}
Tips
- All schemas and used models must have globally unique name
- Return a
{ [statusCode]: payload }
object in a route to take advantages of response body type check and faster JSON serialization - To ensure that client bundle doesn't include unnecessary packages (e.g.
ajv
, fast-json-stringify
, which are only used in server side),
- import packages only from
@ddadaal/next-typed-api-routes/lib/client
in client files, - import types with
import type
clause
Thanks
Roadmap
Development
npm install
npm install --no-save next
License
MIT