The AccessTokenProvider component simplifies authentication by managing JWT tokens for all child components. You provide it with a function that fetches tokens from your backend, and it handles:

  • Fetching the initial JWT token
  • Automatically refreshing expired tokens
  • Distributing tokens to all child components

This eliminates the need to manually handle tokens in each component.

See also Client-side authentication for more information on how to authenticate with Propel.

Here’s an example showing why this is helpful:

Wrap your app with the AccessTokenProvider and pass it the fetchToken function. This will ensure that all child components automatically receive the JWT token:

import { Counter, TimeSeries, Leaderboard, AccessTokenProvider } from '@propeldata/ui-kit'
import { fetchToken } from './utils'

function App() {
  return (
    <AccessTokenProvider fetchToken={fetchToken}>
      <Counter />
      <TimeSeries />
      <Leaderboard />
    </AccessTokenProvider>
  )
}

Preferably the fetchToken function lives outside of the component scope, in case you need to create it within the component scope please wrap it in a useCallback to prevent unnecessary re-renders:

import React, { useCallback } from 'react'
import { Counter, TimeSeries, Leaderboard, AccessTokenProvider } from '@propeldata/ui-kit'

function App() {
  const fetchToken = useCallback(() => {
    // fetching logic

    return accessToken
  }, [deps])

  return (
    <AccessTokenProvider fetchToken={fetchToken}>
      <Counter />
      <TimeSeries />
      <Leaderboard />
    </AccessTokenProvider>
  )
}

If you’d prefer to handle fetching on your own, you can pass the accessToken prop to the AccessTokenProvider. The provided access token will be served to all of its child components:

function App() {
  const [accessToken, setAccessToken] = useState(null)

  return (
    <AccessTokenProvider accessToken={accessToken}>
      <Counter />
      <TimeSeries />
      <Leaderboard />
    </AccessTokenProvider>
  )
}

You can use multiple AccessTokenProvider components in your app, each with its own fetchToken function or accessToken prop. However, avoid nesting them to prevent unexpected behavior.