Hi, I’m Dung Huynh Duc . Nice to meet you.

About Me

I’m a full stack developer. I’m a fast learner and self-taught coder. I often take my time for researching and learning about hot and trending technology.

fastify
trpc

TIL #24 - Workaround for tRPC Fastify adatper CORS policy

blog_hero_TIL #24 - Workaround for tRPC Fastify adatper CORS policy
void app.register(fp(fastifyTRPCPlugin), {
  prefix: "/trpc",
  trpcOptions: {
    router: appRouter,
    createContext,
    responseMeta(opts: any) {
      if (
        opts.errors?.[0]?.code === "METHOD_NOT_SUPPORTED" &&
        String(opts.errors?.[0]?.message ?? "").includes(
          "Unexpected request method OPTIONS"
        )
      ) {
        return {
          status: 204,
          headers: {
            "Access-Control-Allow-Headers": "Content-Type",
            "access-control-allow-origin": "*",
            vary: "Origin",
          },
        };
      }

      return {
        // Enable CORS, refer https://github.com/trpc/trpc/issues/623#issuecomment-878639248
        headers: {
          "Access-Control-Allow-Headers": "Content-Type",
          "access-control-allow-origin": "*",
          vary: "Origin",
        },
      };
    },
  },
});