Skip to content

Commit 848c263

Browse files
docs: add example for using Auth0 outside of React
1 parent a57e504 commit 848c263

1 file changed

Lines changed: 58 additions & 0 deletions

File tree

EXAMPLES.md

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,64 @@ const Posts = () => {
102102
export default Posts;
103103
```
104104

105+
## Use Auth0 outside of React
106+
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+
109+
Using `createAuth0Client` ensures the `auth0-react` telemetry header is set correctly on the client.
110+
111+
```jsx
112+
// auth0-client.js
113+
import { createAuth0Client } from '@auth0/auth0-react';
114+
115+
export const auth0Client = createAuth0Client({
116+
domain: 'YOUR_AUTH0_DOMAIN',
117+
clientId: 'YOUR_AUTH0_CLIENT_ID',
118+
authorizationParams: {
119+
redirect_uri: window.location.origin,
120+
},
121+
});
122+
```
123+
124+
Pass the client to `Auth0Provider`:
125+
126+
```jsx
127+
import { Auth0Provider } from '@auth0/auth0-react';
128+
import { auth0Client } from './auth0-client';
129+
130+
export default function App() {
131+
return (
132+
<Auth0Provider client={auth0Client}>
133+
<MyApp />
134+
</Auth0Provider>
135+
);
136+
}
137+
```
138+
139+
Use the same client instance directly outside React, for example in an axios interceptor:
140+
141+
```js
142+
import axios from 'axios';
143+
import { auth0Client } from './auth0-client';
144+
145+
axios.interceptors.request.use(async (config) => {
146+
const token = await auth0Client.getTokenSilently();
147+
config.headers.Authorization = `Bearer ${token}`;
148+
return config;
149+
});
150+
```
151+
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+
```
162+
105163
## Custom token exchange
106164

107165
Exchange an external subject token for Auth0 tokens using the token exchange flow (RFC 8693):

0 commit comments

Comments
 (0)