Create Route
The createRoute
function is used for defining typesafe and runtime-validated API routes. It provides the ability to define input and output schemas in addition to the route handler. These routes are best suited for handling HTTP requests in a Next.js application.
Usage
Here's an example of using createRoute
to define an API route:
This route can be used in a Next.js API route file. The createRoute
function
returns a handler that can be directly exported as a route handler (GET, POST,
etc.) in Next.js.
API
Function | Description |
---|---|
createRoute() | Creates a new route creator instance. |
.input(schema: ZodType) | Defines the input schema for the route using a Zod schema. |
.output(schema: ZodType) | Defines the output schema for the route using a Zod schema. |
.handler(fn: (input: InputType) => Promise<OutputType>) | Defines the handler function for the route. This function receives the validated input and should return a promise that resolves to the output matching the defined output schema. |
Detailed Example
Testing
You can easily test routes by calling them directly from a testing framework of your choice. Here is an example using Jest: