
Product
Announcing Socket Fix 2.0
Socket Fix 2.0 brings targeted CVE remediation, smarter upgrade planning, and broader ecosystem support to help developers get to zero alerts.
@ddadaal/next-typed-api-routes
Advanced tools
Make Next.js API Routes strongly typed with routes and clients type completion and auto-generated parameter validation
Write a Schema
interface in your API route file, and you get
all at one command!
"baseUrl": "."
in tsconfig.json
compilerOptions
part{
"compilerOptions": {
"baseUrl": "."
}
}
src
dir next.js src directorynpm install --save @ddadaal/next-typed-api-routes
src/pages/api/test.ts
with the following contentimport { 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 } };
});
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
.
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); });
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"
}
}
To convert a normal API Routes to a type checked one, all you need to do is
Schema
interfaceroute
function, specify the name of Schema interface as the type argument and first argumentThe 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.
The shape of Schema interface is defined as follows:
// The name of the schema must be unique across the whole project
interface TestSchema {
// Required. Must be a valid CAPITALIZED string literal type of HTTP method (GET, POST, PATCH)
method: "POST";
// Optional. Define the path param and query (to align with next.js)
query: {
// Supports most type constructs
property?: string | number | AnotherInterface | Pick<{ number: string }, "number">;
/**
* You can also use jsdoc for more specific limits
* You can use keywords and values from JSON Schema Draft-07
* @format email
* @maxLength 50
*/
anotherProperty: string;
}
// Optional. Define the body
body: {
// Supports most type constructs
property?: string | number | AnotherInterface | Pick<{ number: string }, "number">;
}
// Required. Define the responses
responses: {
// Key as response code.
// Only one [200, 300) response should exist. It will be considered by clients as the success response
// If the success response has no payload, the status code must be 204.
200: {
// Supports most type constructs
property?: string | number | AnotherInterface | Pick<{ number: string }, "number">;
};
// If the code has no payload, set the type to null
404: null;
}
}
{ [statusCode]: payload }
object in a route to take advantages of response body type check and faster JSON serializationajv
, fast-json-stringify
, which are only used in server side),
@ddadaal/next-typed-api-routes/lib/client
in client files,import type
clauseAjv
for JSON Schema validationvega/ts-json-schema-generator
for generating json schema from typescriptfast-json-stringify
for faster JSON response serializationfastify
for inspiration or unified validation and serialization using JSON schemanpm install
npm install --no-save next
MIT
FAQs
Make Next.js API Routes strongly typed with routes and clients type completion and auto-generated parameter validation
We found that @ddadaal/next-typed-api-routes demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Product
Socket Fix 2.0 brings targeted CVE remediation, smarter upgrade planning, and broader ecosystem support to help developers get to zero alerts.
Security News
Socket CEO Feross Aboukhadijeh joins Risky Business Weekly to unpack recent npm phishing attacks, their limited impact, and the risks if attackers get smarter.
Product
Socket’s new Tier 1 Reachability filters out up to 80% of irrelevant CVEs, so security teams can focus on the vulnerabilities that matter.