tRPCttRPC
Powered by
DINOD
tRPC•2y ago•
1 reply
DINO

How do I set header value from localStorage or Zustand in tRPC and React?

Hello,

This is my tRPC client in my
App.tsx
App.tsx
:
function App(): JSX.Element {
  const { token } = useAuthStore()
  const [trpcClient] = useState(() =>
    trpcReact.createClient({
      links: [
        httpBatchLink({
          url: 'http://192.168.1.17:3000/trpc',
          fetch(url, options) {
            return fetch(url, {
              ...options,
              credentials: 'include'
            })
          },
          headers: () => {
            return {
              Authorization: `Bearer ${token || ''}`
            }
          }
        })
      ],
      transformer: SuperJSON
    })
  )
function App(): JSX.Element {
  const { token } = useAuthStore()
  const [trpcClient] = useState(() =>
    trpcReact.createClient({
      links: [
        httpBatchLink({
          url: 'http://192.168.1.17:3000/trpc',
          fetch(url, options) {
            return fetch(url, {
              ...options,
              credentials: 'include'
            })
          },
          headers: () => {
            return {
              Authorization: `Bearer ${token || ''}`
            }
          }
        })
      ],
      transformer: SuperJSON
    })
  )

The problem is if the jwt token changes, it doesn't get changed in the trpcClient unless I do something like this but I don't like it:
useEffect(() => {
    if (token)
      setTRPCClientZS(
        trpcReactZS.createClient({
          links: [
            httpBatchLink({
              url: 'http://192.168.1.17:3000/trpc',
              fetch(url, options) {
                return fetch(url, {
                  ...options,
                  credentials: 'include'
                })
              },
              headers: {
                Authorization: `Bearer ${token}`
              }
            })
          ],
          transformer: SuperJSON
        })
      )
  }, [token])
useEffect(() => {
    if (token)
      setTRPCClientZS(
        trpcReactZS.createClient({
          links: [
            httpBatchLink({
              url: 'http://192.168.1.17:3000/trpc',
              fetch(url, options) {
                return fetch(url, {
                  ...options,
                  credentials: 'include'
                })
              },
              headers: {
                Authorization: `Bearer ${token}`
              }
            })
          ],
          transformer: SuperJSON
        })
      )
  }, [token])

What is the best way to set jwt to trpc client?
tRPCJoin
Move Fast & Break Nothing. End-to-end typesafe APIs made easy.
5,015Members
Resources
Recent Announcements

Similar Threads

Was this page helpful?

Similar Threads

Zustand + trpc
Answer OverflowAAnswer Overflow / ❓-help
10mo ago
Adding tRPC HOC breaks zustand
ThomasTThomas / ❓-help
3y ago
zustand + trpc (basic data fetching)
SonSSon / ❓-help
4y ago