Typedef
Typedef16mo ago

Set custom header for fetchRequestHandler

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,
});
}
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,
});
}
11 Replies
Nick
Nick16mo ago
You also need to set the cors response headers, it's not enough to just respond to an options request
Typedef
Typedef16mo ago
yep i was wondering how i can do that with fetchRequestHandler or do i need to set it prior
Nick
Nick16mo ago
It's a fairly common problem, which is often solvable with the npm cors package to save yourself pain
Typedef
Typedef16mo ago
cuz I can easily do it with serverless function like this:
Typedef
Typedef16mo ago
but idk how to do it with edge
Nick
Nick16mo ago
Ah right edge, hm If there's a 1st party way with your edge provider, I'd use that But you can just set the response headers in your code I'm neither a Next or Edge user though unfortunately
Typedef
Typedef16mo ago
how so, im using nextjs aswell .set function doesnt seem to work when using edge
Nick
Nick16mo ago
Honestly I'm not sure, I don't use this tech I'd look for an answer for your specific provider You might be able to modify the response before returning it tRPC generally doesn't deal with CORS stuff though, it's left up to you not to abstract too many things away
Typedef
Typedef16mo ago
i see i just thought u can pass it through createContext although fetchRequestHandler seem to be getting its headers from the req directly
Typedef
Typedef16mo ago
GitHub
docs: outdated next-edge-runtime example · Issue #4048 · trpc/trpc
Area of Improvement Config's runtime edge is not experimental anymore. export const config = { runtime: 'experimental-edge', }; to export const config = { runtime: 'edge', }; Al...
Typedef
Typedef16mo ago
Fixed!