Y0z64Y
tRPC2y ago
1 reply
Y0z64

Get auth token from context when defining httpBatchLink

Im setting up an ApiProvider for react query and I want to get the authorization token for the Authorization header from trpc context since my session is stored there.

My api is defined here
import { type AppRouter } from "../server/api/root";

//** Client provider added for app router compatility **/
export const api = createTRPCReact<AppRouter>({})


And this is the definition of my apiProvider
const token = ""

/** A set of type-safe react-query hooks for your tRPC API.
 * Modified from createTRPCReact to be used with react-query giv3, for app router
 *
 * @see https://trpc.io/docs/react-query
 */
export default function APIProvider({
  children,
}: {
  children: React.ReactNode;
}) {
  const [queryClient] = useState(() => new QueryClient());
  const [apiClient] = useState(() =>
    api.createClient({
      /**
       * Links used to determine request flow from client to server.
       *
       * @see https://trpc.io/docs/links
       */
      links: [
        loggerLink({
          enabled: (opts) =>
            process.env.NODE_ENV === "development" ||
            (opts.direction === "down" && opts.result instanceof Error),
        }),
        httpBatchLink({
          url: `${getBaseUrl()}/api/trpc`,
          headers() {
            return {
              Authorization: `Bearer ${token ?? undefined}`,
            };
          },
        }),
      ],
      transformer: superjson,
    }),
  );
  return (
    <api.Provider client={apiClient} queryClient={queryClient}>
      <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
    </api.Provider>
  );
}


Is there any way to pass the context to the createClient function? or al least just get the context in any way so I can assign the token value to the one in context
Was this page helpful?