Next.js API Type Validation Enhancement #77172
Undertone0809
started this conversation in
Ideas
Replies: 1 comment
-
You can try Example Route: import { NextApiRequest } from 'next-ts-api';
// POST /api/todos
export async function POST(
request: NextApiRequest<{
title: string;
}>
) {
const { title } = await request.json();
const newTodo: Todo = {
id: Math.random().toString(),
title,
completed: false
};
return NextResponse.json(newTodo);
} API Call: import { createNextFetchApi } from "next-ts-api";
import { type ApiRoutes } from "../types/next-ts-api"; // auto generated
export const api = createNextFetchApi<ApiRoutes>();
const response = await api('todos', { // type-safe API route
method: 'POST',
body: {
title: "New Todo" // type-safe body
}
});
const newTodo = await response.json(); // type-safe return data |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Goals
Non-Goals
Background
Currently, Next.js does not provide a built-in solution for API request/response validation. Developers typically rely on one of these approaches:
While these approaches work, they all have drawbacks:
This feature would bridge the gap between simple TypeScript interfaces and full validation libraries, providing a lightweight, built-in solution that leverages the TypeScript type system while adding runtime validation. It would integrate seamlessly with Next.js's API routes, supporting both the simple use cases (with just TypeScript interfaces) and more complex validation scenarios (with Zod or similar libraries).
Similar approaches have been successfully implemented in other frameworks like NestJS (with class-validator) and Fastify (with JSON Schema), demonstrating the value of built-in validation that aligns with the framework's design philosophy.
Proposal
Next.js API Type Validation Enhancement Proposal
Current Problems
Lack of Built-in Type Validation
Frontend-Backend Type Disconnection
Validation Boilerplate
Proposed Solution
1. Simplified Validation with TypeScript Types
2. Zod Support for Complex Validation
3. Support for Different Request Parts
4. Automatic Type Sharing
5. Simple Global Configuration
Implementation Strategy
Benefits
Usage Example Comparison
Current Approach:
Proposed Approach:
Beta Was this translation helpful? Give feedback.
All reactions