T
tRPC

❓-help

Next.js app router catch-all HTTP methods

GGrifn7/17/2023
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?
JHJan Henning7/18/2023
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 }
GGrifn7/20/2023
So obvious 🤦‍♂️ thanks

Looking for more? Join the community!

T
tRPC

❓-help

Join Server