
createNextRouteHandler()
import { createNextRouteHandler } from '@green-stack/schemas/createNextRouteHandler'
- createNextRouteHandler.ts
You can create a new API route by exporting a GET
/ POST
/ UPDATE
/ DELETE
handler assigned to a createNextRouteHandler()
that wraps your “bridged resolver”:
import { updatePost } from '@app/resolvers/updatePost.resolver'
import { createNextRouteHandler } from '@green-stack/schemas/createNextRouteHandler'
/* --- Routes ------------ */
export const UPDATE = createNextRouteHandler(updatePost)
// Automatically extracts (☝️) args from url / search params
// based on the zod 'inputSchema'
// If you want to support e.g. POST (👇), same deal (checks request body too)
export const POST = createNextRouteHandler(updatePost)
How it works
What createNextRouteHandler()
does under the hood:
-
- extract the input from the request context
-
- validate it
-
- call the resolver function with the args (and e.g. token / session / request context)
-
- return the output from your resolver with defaults applied
Check Next.js Route Handlers to understand supported exports (like
GET
orPOST
) and their options.
Restart your dev server or run
npm run link:routes
to make sure your new API route is available.
Related Automations
link-routes
- script
npm run link:routes
This script will:
-
- Scan the
/routes/
folder in any of your non-app workspaces
- Scan the
-
- Find all
route.ts
files that export acreateNextRouteHandler()
function
- Find all
-
- Re-export your
GET
/POST
/PUT
/DELETE
route handlers to the@app/next
workspace
- Re-export your
The goal of this script is so you can define your API routes colocated by feature, instead of grouping by the “API route” type.
Overall, this will keep your features more modular and portable between GREEN stack / FullProduct.dev projects.
The link-routes
script runs automatically on npm run dev
and any production build commands.
add-resolver
- generator
You don’t need to manually create a new API route with createNextRouteHandler()
every time you create a new resolver. You can use the add-resolver
generator to create a new resolver and its API route at once:
npx turbo gen resolver