Auth Headers in Singleton Pattern
The recommended approach for setting up a SPA with tRPC is to use the Singleton Pattern (source). However, many authentication libraries rely on providers and hooks to supply the authenticated user, meaning the
access_token
is only accessible within React land.
Given this, what is the recommended method to include the access_token
in the tRPC headers? Can this be achieved using the Singleton Pattern, or is it necessary to use TRPCProvider
instead?Solution:Jump to solution
GitHub
Introducing the new TanStack React Query integration · trpc trpc · ...
We are excited to announce the new TanStack React Query integration for tRPC is now available on tRPC's next-release. Compared to our classic React Query Integration it's simpler and more T...
4 Replies
I agree with this one, I rely on a hook from clerk to get the token
now I can't use it and pass it on to my headers
what would be the recommended approach?
Solution
GitHub
Introducing the new TanStack React Query integration · trpc trpc · ...
We are excited to announce the new TanStack React Query integration for tRPC is now available on tRPC's next-release. Compared to our classic React Query Integration it's simpler and more T...
👍 I was able to implement it
Since you're using a SPA with something like vite, you can use something like jotai so you can access the token from both inside and outside of react doing something like this:
1. first create the token atom
2. then sync the token atom with your hook
3. Then in your react app you can use either the
useAuthToken
to use the atom as a single source of truth or just keep using your provider hook
4. For outside of react like trpc or api calls, you can just call the getAuthToken
function which will retreive the value from the atom
There's also a simplified version of this if you don't care about using a single source of truth and don't already have jotai in your app and don't want to add it, using regular js, but i recommend the first approach
then in the trpc singleton you can just the authToken directly