kwhitley / itty-router

A little router.
MIT License
1.8k stars 79 forks source link

How to Use Itty Router with Next.js? #194

Closed c1DeepInside closed 1 year ago

c1DeepInside commented 1 year ago

Next with itty-router

I'm currently exploring the possibility of integrating itty router into a Next.js project. My main concern revolves around the fact that Next.js comes with its own built-in routing system. I'm curious about how these two can coexist or if it's even feasible to implement itty router within the Next.js environment.

c1DeepInside commented 1 year ago

Example to use itty-router with next

Here how to use Next with itty router openapi

To integrate itty router with Next.js, you can create a custom API route that captures all requests. For instance, you might have a route like app/api/gpt/[slug].ts.

Use router.get or router.post like default moves with itty-router

import { Router } from 'itty-router'

const router = Router()

router.all('*', () => new Response('404 Not Found...', { status: 200 }))

In Next.js 14, to intercept GET and POST requests and pass them to itty router, you need to set up your API routes to forward these requests to therouter. This can be done by returning router.handle(req) within your API route handlers.

export async function POST(req: Request) {
  return router.handle(req)
}

export async function GET(req: Request) {
  return router.handle(req)
}