Bearer Auth React Context
(Now that's a mouthful.)
Bearer Auth React Context is a React Context meant to simplify integrations with APIs using Bearer Token Authorization.
Bearer Token Authentication a common authentication method. For details, see RFC6750, or various other online resources.
While handling bearer token itself is straightforward, it needs to be refreshed, and that's where things get icky. I couldn't really find a sensible way of doing that in React (for example when using React-Query), hence this library.
Bearer Auth React Context provides React Context and associated hooks that:
- are network library (fetch, axios, etc.) agnostic
- automatically handle token refresh
- handles various edge cases (e.g.: if two requests fail at the same time, only one refresh request is sent)
- store Bearer auth token in
localStorage - provide convenient wrapper for network calls
- provide callbacks for when token refresh succeeds or fails
- plays nice with React-Query
Getting Started#
You need a working React project. Bootstrapped with Next.js, Create React App, manually, whatever your prefer - as long as it's React.
- Install
bearer-auth-react-contextwith your favourite package manager, e.g.:
yarn add bearer-auth-react-context- Wrap your app with
<BearerAuthContextProvider>, e.g.:
const App = () => { return ( <BearerAuthContextProvider fetcherConfig={fetcherConfig} hasTokenExpired={hasTokenExpired} refreshHandler={handleTokenRefresh} > <MainPage /> </BearerAuthContextProvider> );};
ReactDOM.render(<App />, document.getElementById('root'));- Provide required props:
fetcherConfig- generic configuration object (typically including API URL) passed to each query functionhasTokenExpired- function used to decide whether request failed because of expired tokenrefreshHandler- function that performs actual token refresh
For more details, see Handling Refresh.
Wrap all your API calls with
useBearerAuthWrapper(). For more details, see Making Network Calls.You're good to go!
Sample app#
Living, breathing example is available here.
Log in as test/test, open browser devtools and click away. Token expires every 10 seconds.