#TIL 24 - Workaround for tRPC Fastify adapter CORS policy | ProductsWay

#TIL 24 - Workaround for tRPC Fastify adapter CORS policy

Mar 7, 2022 · Dung Huynh

What

Handle CORS preflight (OPTIONS) requests in tRPC's Fastify adapter via responseMeta.

Why

Browsers send an OPTIONS request before cross-origin POSTs. The tRPC Fastify adapter rejects OPTIONS with METHOD_NOT_SUPPORTED, so the browser never sends the real request. Returning 204 with CORS headers in responseMeta satisfies the preflight check.

How

app.register(fp(fastifyTRPCPlugin), {
  prefix: "/trpc",
  trpcOptions: {
    router: appRouter,
    createContext({ req }) {
      return { requestMethod: req.method };
    },
    responseMeta({ ctx, errors }) {
      // Handle OPTIONS preflight
      if (
        ctx?.requestMethod === "OPTIONS" &&
        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",
        },
      };
    },
  },
});