T

tRPC

โ“-help

Join Server

Set custom header for fetchRequestHandler

00xTypedef3/21/2023
Is this possible? currently getting cors issue. Trying to use nextjs's edge function with trpc..

import { type NextRequest } from "next/server";
import { appRouter, createContext } from "api";
import { fetchRequestHandler } from "@trpc/server/adapters/fetch";

export const config = {
  runtime: "edge",
};

export default async function handler(req: NextRequest) {
  if (req.method === "OPTIONS") {
    return new Response(null, {
      status: 200,
    });
  }

  return fetchRequestHandler({
    endpoint: "/api/trpc",
    router: appRouter,
    createContext,
    req,
    onError:
      process.env.NODE_ENV === "development"
        ? ({ path, error }) => {
            console.error(`[tRPC] failed on ${path}: ${error}`);
          }
        : undefined,
  });
}
Nnlucas3/21/2023
You also need to set the cors response headers, it's not enough to just respond to an options request
00xTypedef3/21/2023
yep i was wondering how i can do that
00xTypedef3/21/2023
with fetchRequestHandler
00xTypedef3/21/2023
or do i need to set it prior
Nnlucas3/21/2023
It's a fairly common problem, which is often solvable with the npm cors package to save yourself pain
00xTypedef3/21/2023
cuz I can easily do it with serverless function like this:
00xTypedef3/21/2023
but idk how to do it with edge
Nnlucas3/21/2023
Ah right edge, hm
Nnlucas3/21/2023
If there's a 1st party way with your edge provider, I'd use that
Nnlucas3/21/2023
But you can just set the response headers in your code
Nnlucas3/21/2023
I'm neither a Next or Edge user though unfortunately
00xTypedef3/21/2023
how so, im using nextjs aswell
00xTypedef3/21/2023
.set function doesnt seem to work
00xTypedef3/21/2023
when using edge
Nnlucas3/21/2023
Honestly I'm not sure, I don't use this tech
Nnlucas3/21/2023
I'd look for an answer for your specific provider
Nnlucas3/21/2023
You might be able to modify the response before returning it
Nnlucas3/21/2023
tRPC generally doesn't deal with CORS stuff though, it's left up to you not to abstract too many things away
00xTypedef3/21/2023
i see i just thought u can pass it through createContext
00xTypedef3/21/2023
although fetchRequestHandler seem to be getting its headers from the req directly
00xTypedef3/24/2023
Fixed!