T
TanStack•10mo ago
ratty-blush

Using TRPC with procedures that require auth on a server

Anyone has an example of the following: - Route that uses TRPC procedure. It's called both in loader(saved to queryCache) and then in component. - Procedure is protected by auth that reads cookie to check for user The problem I have is that I can't just create createTRPCClient with httpBatchLink url because to access auth cookie when making calls from server I'll need to manually pass headers to second call. In Next.js I can solve it by using a different caller in server components, probably even createCallerFactory which uses trpc directly. However here I'm not sure how to do that. The only working solution I have is to create a server function, but that's not convenient. Is there a way to run different code on SSR and client-side, while avoiding sending SSR code to client, or some other way to solve it? (I dont think it matters but I don't use @trpc/react-query and manage my keys manually)
3 Replies
sunny-green
sunny-green•10mo ago
GitHub
tanstack-start-trpc/app/api.ts at main · tinrab/tanstack-start-trpc
Example of using tRPC with TanStack Start. Contribute to tinrab/tanstack-start-trpc development by creating an account on GitHub.
sunny-green
sunny-green•10mo ago
and also update the headers like, so that the cookie is available on the first request
unstable_httpBatchStreamLink({
transformer: superjson,
url: get_trpc_url(),
async headers() {
if (import.meta.env.SSR) {
try {
const { getHeaders } = await import("vinxi/http");
return getHeaders();
} catch (e) {
console.error(e);
}
}

return {};
},
}),
unstable_httpBatchStreamLink({
transformer: superjson,
url: get_trpc_url(),
async headers() {
if (import.meta.env.SSR) {
try {
const { getHeaders } = await import("vinxi/http");
return getHeaders();
} catch (e) {
console.error(e);
}
}

return {};
},
}),
I'm not 100% sure it works because i don't use TRPC anymore because the serverFn's from tanstack give me almost the same 🙂 But I got it to work with cookie auth before moving away
ratty-blush
ratty-blushOP•10mo ago
Thank you if (import.meta.env.SSR) { did the trick

Did you find this page helpful?