brumbrum_brumB
tRPC17mo ago
1 reply
brumbrum_brum

Fastify + TRPC on Vercel

I am having trouble hosting a Fastify + TRPC server on Vercel.
I have tried two different vercel.json setups, but they both do not work for each reasons:
{
  "rewrites": [
    {
      "source": "/(.*)",
      "destination": "/index.js"
    }
  ]
}

^^^This just shows the built code in the browser, no matter what route I go to.

{
  "builds": [{ "src": "./index.js", "use": "@vercel/node" }],
  "routes": [{ "src": "/(.*)", "dest": "/" }]
}

^^This just shows a 404 page from Vercel.

This is my index.ts file (Built to index.js):
import { fastifyTRPCPlugin, FastifyTRPCPluginOptions } from "@trpc/server/adapters/fastify";
import { VercelRequest, VercelResponse } from "@vercel/node";
import fastify from "fastify";
import { createContext } from "./context";
import { appRouter, type AppRouter } from "./router";
import dotenv from "dotenv";

export type { AppRouter } from "./router";

dotenv.config();

const server = fastify({});

server.register(fastifyTRPCPlugin, {
  prefix: "/",
  trpcOptions: {
    router: appRouter,
    createContext,

    onError({ path, error }) {
      console.error(`Error in tRPC handler on path '${path}':`, error);
    },
  } satisfies FastifyTRPCPluginOptions<AppRouter>["trpcOptions"],
});


export default async (req: VercelRequest, res: VercelResponse) => {
  await server.ready();
  server.server.emit("request", req, res);
};
Was this page helpful?