kwhitley / itty-router

A little router.
MIT License
1.76k stars 78 forks source link

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

Closed c1DeepInside closed 10 months ago

c1DeepInside commented 10 months 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 10 months 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)
}