|
3 | 3 | - [Use with a Class Component](#use-with-a-class-component) |
4 | 4 | - [Protect a Route](#protect-a-route) |
5 | 5 | - [Call an API](#call-an-api) |
| 6 | +- [Use Auth0 outside of React](#use-auth0-outside-of-react) |
6 | 7 | - [Protecting a route in a `react-router-dom v6` app](#protecting-a-route-in-a-react-router-dom-v6-app) |
7 | 8 | - [Protecting a route in a Gatsby app](#protecting-a-route-in-a-gatsby-app) |
8 | 9 | - [Protecting a route in a Next.js app (in SPA mode)](#protecting-a-route-in-a-nextjs-app-in-spa-mode) |
@@ -104,7 +105,7 @@ export default Posts; |
104 | 105 |
|
105 | 106 | ## Use Auth0 outside of React |
106 | 107 |
|
107 | | -If you need to access the `Auth0Client` outside of the React tree — for example in middleware, axios interceptors, or TanStack Router loaders — use `createAuth0Client` to create a shared instance and pass it to `Auth0Provider` via the `client` prop. |
| 108 | +If you need to share an `Auth0Client` instance between the React tree and code that has no access to React's lifecycle — such as Redux middleware — use `createAuth0Client` to create a shared instance and pass it to `Auth0Provider` via the `client` prop. |
108 | 109 |
|
109 | 110 | Using `createAuth0Client` ensures the `auth0-react` telemetry header is set correctly on the client. |
110 | 111 |
|
@@ -136,29 +137,21 @@ export default function App() { |
136 | 137 | } |
137 | 138 | ``` |
138 | 139 |
|
139 | | -Use the same client instance directly outside React, for example in an axios interceptor: |
| 140 | +Use the same client instance in Redux middleware: |
140 | 141 |
|
141 | 142 | ```js |
142 | | -import axios from 'axios'; |
143 | 143 | import { auth0Client } from './auth0-client'; |
144 | 144 |
|
145 | | -axios.interceptors.request.use(async (config) => { |
146 | | - const token = await auth0Client.getTokenSilently(); |
147 | | - config.headers.Authorization = `Bearer ${token}`; |
148 | | - return config; |
149 | | -}); |
| 145 | +export const authMiddleware = store => next => async action => { |
| 146 | + if (action.requiresAuth) { |
| 147 | + const token = await auth0Client.getTokenSilently(); |
| 148 | + return next({ ...action, token }); |
| 149 | + } |
| 150 | + return next(action); |
| 151 | +}; |
150 | 152 | ``` |
151 | 153 |
|
152 | | -Or in a TanStack Router middleware: |
153 | | - |
154 | | -```js |
155 | | -import { auth0Client } from './auth0-client'; |
156 | | - |
157 | | -export const authMiddleware = createMiddleware().server(async ({ next }) => { |
158 | | - const token = await auth0Client.getTokenSilently(); |
159 | | - return next({ context: { token } }); |
160 | | -}); |
161 | | -``` |
| 154 | +> **Note:** `getTokenSilently()` requires an active session. Ensure `Auth0Provider` has mounted and completed initialization before calling it outside React. |
162 | 155 |
|
163 | 156 | ## Custom token exchange |
164 | 157 |
|
|
0 commit comments