SSR with TRPC on App Router
I have a TRPC instance that's using App Router and
I'm gonna admit, I haven't the slightest clue how to even start trying to fix this.
createTRPCNext
, but when doing SSR, headers aren't passed properly, ctx.req
is always undefined, and so my code always throws UNAUTHORIZED
.
Here's how I'm creating it:
export const api = createTRPCNext<AppRouter>({
ssr: true,
ssrPrepass,
transformer: SuperJSON,
config({ ctx }) {
if (typeof window === "undefined") {
return {
links: [
loggerLink({
enabled: (op) =>
process.env.NODE_ENV === "development" ||
(op.direction === "down" && op.result instanceof Error),
}),
httpBatchStreamLink({
url: `${getBaseUrl()}/api/trpc`,
headers: () => {
return ctx?.req?.headers ?? {};
},
transformer: SuperJSON,
}),
],
};
}
return {
links: [
loggerLink({
enabled: (op) =>
process.env.NODE_ENV === "development" ||
(op.direction === "down" && op.result instanceof Error),
}),
httpBatchStreamLink({
transformer: SuperJSON,
url: `${getBaseUrl()}/api/trpc`,
headers: () => {
const headers = new Headers();
headers.set("x-trpc-source", "nextjs-react");
return headers;
},
}),
],
};
},
});
export const api = createTRPCNext<AppRouter>({
ssr: true,
ssrPrepass,
transformer: SuperJSON,
config({ ctx }) {
if (typeof window === "undefined") {
return {
links: [
loggerLink({
enabled: (op) =>
process.env.NODE_ENV === "development" ||
(op.direction === "down" && op.result instanceof Error),
}),
httpBatchStreamLink({
url: `${getBaseUrl()}/api/trpc`,
headers: () => {
return ctx?.req?.headers ?? {};
},
transformer: SuperJSON,
}),
],
};
}
return {
links: [
loggerLink({
enabled: (op) =>
process.env.NODE_ENV === "development" ||
(op.direction === "down" && op.result instanceof Error),
}),
httpBatchStreamLink({
transformer: SuperJSON,
url: `${getBaseUrl()}/api/trpc`,
headers: () => {
const headers = new Headers();
headers.set("x-trpc-source", "nextjs-react");
return headers;
},
}),
],
};
},
});
0 Replies