Grifn
Grifn2y 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 Henning2y 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
GrifnOP2y ago
So obvious 🤦‍♂️ thanks

Did you find this page helpful?