#Using TRPC with procedures that require auth on a server

4 messages · Page 1 of 1 (latest)

edgy sonnet
#

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)

nova karma
#

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 {};
            },
        }),
#

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