#TIL 24 - Workaround for tRPC Fastify adapter CORS policy

Mar 7, 2022 · Dung Huynh

What

Fix CORS preflight (OPTIONS) requests in tRPC with Fastify adapter.

Why

tRPC Fastify adapter doesn't handle OPTIONS requests by default, causing browser CORS errors.

How

app.register(fp(fastifyTRPCPlugin), {
  prefix: "/trpc",
  trpcOptions: {
    router: appRouter,
    responseMeta({ errors }) {
      // Handle OPTIONS preflight
      if (errors?.[0]?.code === "METHOD_NOT_SUPPORTED") {
        return {
          status: 204,
          headers: {
            "Access-Control-Allow-Headers": "Content-Type",
            "access-control-allow-origin": "*",
            vary: "Origin",
          },
        };
      }
      // Regular CORS headers
      return {
        headers: {
          "Access-Control-Allow-Headers": "Content-Type",
          "access-control-allow-origin": "*",
          vary: "Origin",
        },
      };
    },
  },
});