Grifn
Grifn15mo ago

Next.js app router catch-all HTTP methods

The app router already supports the catch-all file for route resolution, but AFAIK still expects separately method exports like export function GET(). I think this means we can't provide the tRPC NextApiHandler from the app router and we still need to use the pages directory (not a big deal but adding a whole extra directory just for the tRPC route currently). Any way to provide the tRPC Next handler from the app router?
2 Replies
Jan Henning
Jan Henning15mo ago
Hi. You can create a handler function and export it as both GET and POST. For example, here's how mine looks. Yours may look different, but the same thing applies to how you can export it 🙂
import { fetchRequestHandler } from "@trpc/server/adapters/fetch"
import { appRouter } from "~/server/routers/_app"
import { createContext } from "~/server/trpc"

const handler = (req: Request) =>
fetchRequestHandler({
endpoint: "/api/trpc",
req,
router: appRouter,
createContext
})

export { handler as GET, handler as POST }
import { fetchRequestHandler } from "@trpc/server/adapters/fetch"
import { appRouter } from "~/server/routers/_app"
import { createContext } from "~/server/trpc"

const handler = (req: Request) =>
fetchRequestHandler({
endpoint: "/api/trpc",
req,
router: appRouter,
createContext
})

export { handler as GET, handler as POST }
Grifn
Grifn15mo ago
So obvious 🤦‍♂️ thanks