Skip to content

How to pass authorization header to every single API calls? #51

Description

@gablabelle

Hello,

Could you share an example of how you actually pass headers to requests? For example, I need to pass an authorization header to all my API calls which is a pretty common pattern.

For now we do the following:

import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import * as Client from '@my/client'
import { useToken } from './token'

const queryClient = new QueryClient()

Client.setBaseUrl('https://example.com')

export function ClientProvider({ children }: { children: React.ReactNode }) {
  const { token } = useToken()

  if (token) {
    Client.setFetchFactory(() => ({
      fetch: (input: RequestInfo | URL, init?: RequestInit) => {
        const headers = new Headers(init?.headers)
        headers.set('Authorization', `Bearer ${token}`)
        return window.fetch(input, { ...init, headers })
      },
    }))
  }

  return <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
}

Many thanks for your time and help.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions