### Install Dependencies and Start Development Server Source: https://github.com/auth0/auth0-react/blob/main/CONTRIBUTING.md Use these commands to install project dependencies and launch the local development server for testing changes. The server runs at http://localhost:3000 and supports live reloading. ```bash npm install npm start ``` -------------------------------- ### MFA Handling Example Source: https://github.com/auth0/auth0-react/blob/main/docs/interfaces/Auth0ContextInterface.html Example demonstrating how to handle Multi-Factor Authentication (MFA) flows, including enrollment, challenge, and verification, using the `useAuth0` hook. ```APIDOC ## MFA Handling Example ### Description This example shows how to use the `useAuth0` hook to manage MFA flows. It covers scenarios where MFA is required, including checking for enrollment needs, enrolling new factors, challenging the user, and verifying their input. ### Method `getAccessTokenSilently` and `mfa` methods from `useAuth0` hook. ### Endpoint N/A (Client-side SDK functionality) ### Request Example ```javascript const { mfa, getAccessTokenSilently } = useAuth0(); try { await getAccessTokenSilently(); } catch (error) { if (error.error === 'mfa_required') { // Check if enrollment is needed const factors = await mfa.getEnrollmentFactors(error.mfa_token); if (factors.length > 0) { // Enroll in OTP const enrollment = await mfa.enroll({ mfaToken: error.mfa_token, factorType: 'otp' }); console.log('QR Code:', enrollment.barcodeUri); } // Get authenticators and challenge const authenticators = await mfa.getAuthenticators(error.mfa_token); await mfa.challenge({ mfaToken: error.mfa_token, challengeType: 'otp', authenticatorId: authenticators[0].id }); // Verify with user's code const tokens = await mfa.verify({ mfaToken: error.mfa_token, otp: userCode }); } } ``` ### Response N/A (This is a client-side code example demonstrating a flow.) ``` -------------------------------- ### Auth0Provider Configuration (v1) Source: https://github.com/auth0/auth0-react/blob/main/MIGRATION_GUIDE.md Example of configuring Auth0Provider with SDK configuration and Auth0 parameters at the root level in v1. ```jsx ReactDOM.render( , document.getElementById('app') ); ``` -------------------------------- ### Auth0Provider Configuration (v2) Source: https://github.com/auth0/auth0-react/blob/main/MIGRATION_GUIDE.md Example of configuring Auth0Provider with SDK configuration at the root and Auth0 parameters within `authorizationParams` in v2. ```jsx ReactDOM.render( , document.getElementById('app') ); ``` -------------------------------- ### Use Auth0Client in TanStack Start Middleware Source: https://github.com/auth0/auth0-react/blob/main/EXAMPLES.md Utilize the shared Auth0Client instance within TanStack Start client function middleware to obtain tokens for API requests. This example demonstrates fetching a token silently and adding it to the Authorization header. ```js import { createMiddleware } from '@tanstack/react-start'; import { auth0Client } from './auth0-client'; export const authMiddleware = createMiddleware({ type: 'function' }).client( async ({ next }) => { const token = await auth0Client.getTokenSilently(); return next({ headers: { Authorization: `Bearer ${token}`, }, }); }, ); ``` -------------------------------- ### Install Auth0 React SDK using npm Source: https://github.com/auth0/auth0-react/blob/main/README.md Use this command to add the Auth0 React SDK to your project when using npm as your package manager. ```bash npm install @auth0/auth0-react ``` -------------------------------- ### Install Auth0 React SDK using yarn Source: https://github.com/auth0/auth0-react/blob/main/README.md Use this command to add the Auth0 React SDK to your project when using yarn as your package manager. ```bash yarn add @auth0/auth0-react ``` -------------------------------- ### Run Integration Tests Source: https://github.com/auth0/auth0-react/blob/main/CONTRIBUTING.md To run integration tests, first set up the example applications as per their README. Then, execute this command, providing your Auth0 user credentials as environment variables. Ensure the user has 'read:users' permissions. ```bash CYPRESS_USER_EMAIL={YOUR USER} CYPRESS_USER_PASSWORD={YOUR PW} npm run test:integration ``` -------------------------------- ### Execute logic before authentication Source: https://github.com/auth0/auth0-react/blob/main/docs/interfaces/WithAuthenticationRequiredOptions.html Allows executing logic before the user is redirected to the login page. This example shows tracking a login event. ```typescript withAuthenticationRequired(Profile, { onBeforeAuthentication: () => { analyticsLibrary.track('login_triggered'); } }) ``` -------------------------------- ### Open URL for Auth0 Redirect (v2) Source: https://github.com/auth0/auth0-react/blob/main/MIGRATION_GUIDE.md Example of using `loginWithRedirect` with a custom `openUrl` function to handle redirects externally, replacing `buildAuthorizeUrl`. ```ts const { loginWithRedirect } = useAuth0(); await loginWithRedirect({ async openUrl(url) { await Browser.open({ url }); }, }); ``` -------------------------------- ### Get Configuration Source: https://github.com/auth0/auth0-react/blob/main/docs/interfaces/Auth0ContextInterface.html Retrieves a readonly copy of the SDK's initialization configuration, including the domain and client ID. Useful for inspecting current settings. ```typescript const config = getConfiguration();// { domain: 'tenant.auth0.com', clientId: 'abc123' } ``` ```typescript const auth0 = new Auth0Client({ domain: 'tenant.auth0.com', clientId: 'abc123'});const config = auth0.getConfiguration();// { domain: 'tenant.auth0.com', clientId: 'abc123' } ``` -------------------------------- ### Example Scope for Token Exchange Source: https://github.com/auth0/auth0-react/blob/main/docs/types/CustomTokenExchangeOptions.html Provides a space-separated list of OAuth 2.0 scopes being requested. These scopes are subject to API authorization policies configured in Auth0. ```string "openid profile email read:data write:data" ``` -------------------------------- ### App Component with React Router Setup Source: https://context7.com/auth0/auth0-react/llms.txt The main App component that sets up `BrowserRouter`, `Auth0ProviderWithNavigate`, and defines routes for Home, Dashboard, and Profile pages, including a catch-all for invalid paths. ```jsx // App with routing function App() { return ( } /> } /> } /> } /> ); } export default App; ``` -------------------------------- ### Specify return URL after login (string) Source: https://github.com/auth0/auth0-react/blob/main/docs/interfaces/WithAuthenticationRequiredOptions.html Add a path for the `onRedirectCallback` handler to return the user to after login. This example sets a static return path. ```typescript withAuthenticationRequired(Profile, { returnTo: '/profile' }) ``` -------------------------------- ### Auth0Client with Custom openUrl - Capacitor Browser Source: https://github.com/auth0/auth0-react/blob/main/docs/interfaces/RedirectLoginOptions.html Example of initializing Auth0Client with a custom async openUrl function using Capacitor's Browser module for handling redirects. This is suitable for Capacitor-based applications. ```typescript import { Browser } from '@capacitor/browser'; const client = new Auth0Client({ async openUrl(url) { await Browser.open({ url }); } }); ``` -------------------------------- ### Create Fetcher and Make Authenticated Requests Source: https://context7.com/auth0/auth0-react/llms.txt Use `createFetcher` to instantiate a fetcher with authentication capabilities. Configure it with a base URL and a custom `getAccessToken` function. Then, use the `fetcher.fetchWithAuth` method for GET and POST requests, ensuring proper error handling and response processing. ```jsx import React, { useEffect, useState } from 'react'; import { useAuth0 } from '@auth0/auth0-react'; function SecureApiClient() { const { createFetcher, getAccessTokenSilently, isAuthenticated } = useAuth0(); const [posts, setPosts] = useState([]); const [error, setError] = useState(null); useEffect(() => { if (!isAuthenticated) return; const fetchPosts = async () => { // Create a fetcher with configuration const fetcher = createFetcher({ baseUrl: 'https://api.example.com', dpopNonceId: 'api_requests', // Required if DPoP is enabled // Custom token retrieval with specific params getAccessToken: () => getAccessTokenSilently({ authorizationParams: { audience: 'https://api.example.com/', scope: 'read:posts write:posts' } }) }); try { // Simple GET request const response = await fetcher.fetchWithAuth('/posts', { method: 'GET', headers: { 'Accept': 'application/json' } }); if (!response.ok) { throw new Error(`HTTP ${response.status}: ${response.statusText}`); } const data = await response.json(); setPosts(data); // POST request with body const newPost = await fetcher.fetchWithAuth('/posts', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ title: 'New Post', content: 'Hello!' }) }); console.log('Created post:', await newPost.json()); } catch (e) { setError(e.message); console.error('API error:', e); } }; fetchPosts(); }, [createFetcher, getAccessTokenSilently, isAuthenticated]); if (!isAuthenticated) return
Please log in
; if (error) return
Error: {error}
; return ( ); } export default SecureApiClient; ``` -------------------------------- ### Logout with logoutParams (v2) Source: https://github.com/auth0/auth0-react/blob/main/MIGRATION_GUIDE.md Example of calling the logout method with SDK configuration and Auth0 specific parameters nested within `logoutParams` in v2. ```ts await logout({ clientId: '', logoutParams: { federated: true / false, returnTo: '', any_custom_property: 'value', }, }); ``` -------------------------------- ### Open URL for Logout Redirect (v2) Source: https://github.com/auth0/auth0-react/blob/main/MIGRATION_GUIDE.md Example of using `logout` with a custom `openUrl` function to handle redirects externally, replacing `buildLogoutUrl`. ```ts const { logout } = useAuth0(); client.logout({ async openUrl(url) { await Browser.open({ url }); }, }); ``` -------------------------------- ### Specify return URL after login (function) Source: https://github.com/auth0/auth0-react/blob/main/docs/interfaces/WithAuthenticationRequiredOptions.html Add a path for the `onRedirectCallback` handler to return the user to after login. This example dynamically sets the return path based on the current window hash. ```typescript withAuthenticationRequired(Profile, { returnTo: () => window.location.hash.substr(1) }) ``` -------------------------------- ### Configure SDK for Token Vault and MRRT Source: https://github.com/auth0/auth0-react/blob/main/EXAMPLES.md Configure the `Auth0Provider` with an audience for the resource server, enable refresh tokens and MRRT, and enable DPoP for My Account API interactions. This setup is necessary for using the Token Vault feature. ```jsx ' // The API that will use the tokens from the Token Vault }} useRefreshTokens={true} useMrrt={true} useDpop={true} > ``` -------------------------------- ### Error.captureStackTrace Example Source: https://github.com/auth0/auth0-react/blob/main/docs/classes/PopupTimeoutError.html Demonstrates how to use Error.captureStackTrace to create a stack trace on a target object, optionally omitting frames above a specified constructor. This is useful for hiding implementation details. ```javascript const myObject = {};Error.captureStackTrace(myObject);myObject.stack; // Similar to `new Error().stack` ``` ```javascript function a() { b();}function b() { c();}function c() { // Create an error without stack trace to avoid calculating the stack trace twice. const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; const error = new Error(); Error.stackTraceLimit = stackTraceLimit; // Capture the stack trace above function b Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace throw error;}a(); ``` -------------------------------- ### MFA Enroll Flow Response Example Source: https://github.com/auth0/auth0-react/blob/main/EXAMPLES.md This JSON structure represents the response when MFA is required and the user needs to enroll an authenticator, indicating an enroll flow. ```json { "error": "mfa_required", "error_description": "Multifactor authentication required", "mfa_token": "Fe26.2*...", "mfa_requirements": { "enroll": [ { "type": "otp" }, { "type": "phone" }, { "type": "push-notification" } ... ] } } ``` -------------------------------- ### Custom Redirect Method with openUrl (v2) Source: https://github.com/auth0/auth0-react/blob/main/MIGRATION_GUIDE.md Example of using `loginWithRedirect` with a custom `openUrl` function to control the redirect behavior, replacing the removed `redirectMethod` option. ```ts const { loginWithRedirect } = useAuth0(); await loginWithRedirect({ async openUrl(url) { window.location.replace(url); }, }); ``` -------------------------------- ### Auth0Client with Custom openUrl - Default Browser Source: https://github.com/auth0/auth0-react/blob/main/docs/interfaces/RedirectLoginOptions.html Example of initializing Auth0Client with a custom openUrl function to handle redirects using window.location.replace. This is useful for controlling the redirect behavior. ```typescript const client = new Auth0Client({ openUrl(url) { window.location.replace(url); } }); ``` -------------------------------- ### Retrieve Auth0 SDK Configuration Source: https://context7.com/auth0/auth0-react/llms.txt Use the `getConfiguration` method to get a readonly copy of the SDK initialization configuration. Useful for debugging or building custom Auth0 URLs. ```jsx import React from 'react'; import { useAuth0 } from '@auth0/auth0-react'; function ConfigDebug() { const { getConfiguration, isAuthenticated } = useAuth0(); const config = getConfiguration(); const buildCustomUrl = () => { // Use config to build custom URLs const authorizeUrl = new URL(`https://${config.domain}/authorize`); authorizeUrl.searchParams.set('client_id', config.clientId); authorizeUrl.searchParams.set('response_type', 'code'); authorizeUrl.searchParams.set('redirect_uri', window.location.origin); return authorizeUrl.toString(); }; return (

SDK Configuration

Domain: {config.domain}

Client ID: {config.clientId}

Custom Authorize URL: {buildCustomUrl()}

Auth Status: {isAuthenticated ? 'Authenticated' : 'Not authenticated'}

); } export default ConfigDebug; ``` -------------------------------- ### Example of Custom Parameters for Auth0 Actions Source: https://github.com/auth0/auth0-react/blob/main/docs/types/CustomTokenExchangeOptions.html Illustrates how to include custom parameters for Auth0 Action processing within the token exchange options. These parameters are accessible in Action code via `event.request.body`. ```json { custom_parameter: "session_context", device_fingerprint: "a3d8f7...", } ``` -------------------------------- ### Example Audience for Token Exchange Source: https://github.com/auth0/auth0-react/blob/main/docs/types/CustomTokenExchangeOptions.html Specifies the target audience for the requested Auth0 token. This value must exactly match an API identifier configured in your Auth0 tenant. ```string "https://api.your-service.com/v1" ``` -------------------------------- ### Configure Auth0Provider for React 18+ Source: https://github.com/auth0/auth0-react/blob/main/README.md Wrap your application with Auth0Provider to configure the SDK. Ensure you replace 'YOUR_AUTH0_DOMAIN' and 'YOUR_AUTH0_CLIENT_ID' with your actual Auth0 credentials. This setup is for React versions 18 and above. ```jsx import React from 'react'; import { createRoot } from 'react-dom/client'; import { Auth0Provider } from '@auth0/auth0-react'; import App from './App'; const root = createRoot(document.getElementById('app')); root.render( ); ``` -------------------------------- ### MFA Challenge Flow Response Example Source: https://github.com/auth0/auth0-react/blob/main/EXAMPLES.md This JSON structure represents the response when MFA is required and the user has existing enrolled authenticators, indicating a challenge flow. ```json { "error": "mfa_required", "error_description": "Multifactor authentication required", "mfa_token": "Fe26.2*...", "mfa_requirements": { "challenge": [ { "type": "otp" }, { "type": "email" } ... ] } } ``` -------------------------------- ### Example Subject Token for Exchange Source: https://github.com/auth0/auth0-react/blob/main/docs/types/CustomTokenExchangeOptions.html Demonstrates the format of a JWT subject token that will be exchanged for Auth0 tokens. This token must be cryptographically validated in Auth0 Actions with replay attack protection. ```string "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c" ``` -------------------------------- ### Get Access Token with Popup Source: https://github.com/auth0/auth0-react/blob/main/docs/interfaces/Auth0ContextInterface.html Obtains an access token interactively by opening a popup window. Generates random 'state' and 'nonce' parameters. Results are valid according to their expiration times. ```typescript const token = await getTokenWithPopup(options, config); ``` -------------------------------- ### Connect Account with Redirect - With Custom Open URL Handler Source: https://github.com/auth0/auth0-react/blob/main/docs/interfaces/RedirectConnectAccountOptions.html Provide a custom function to handle the redirect URL using the `openUrl` parameter. This allows you to control how the redirect is opened, for example, using a custom browser API. ```javascript await auth0.connectAccountWithRedirect({ connection: 'google-oauth2', openUrl: async (url) => { myBrowserApi.open(url); } }); ``` -------------------------------- ### Handle MfaRequiredError in Auth0 SDK Source: https://github.com/auth0/auth0-react/blob/main/docs/interfaces/MfaApiClient.html This example shows how to catch an MfaRequiredError after attempting to get a silent token. If caught, it retrieves the available authenticators using the provided mfaToken to continue the MFA flow. ```javascript try { await auth0.getTokenSilently({ authorizationParams: { audience: 'https://api.example.com' } }); } catch (e) { if (e instanceof MfaRequiredError) { // SDK automatically stores context for this mfaToken const authenticators = await auth0.mfa.getAuthenticators({ mfaToken: e.mfa_token }); // ... complete MFA flow } } ``` -------------------------------- ### Initialize Auth0Provider Source: https://github.com/auth0/auth0-react/blob/main/static/index.html Set up the Auth0Provider with your Auth0 domain, client ID, and other configuration options. Use a key based on the configuration to ensure re-renders when settings change. ```javascript const App = () => { const [config, setConfig] = useLocalStorage('auth0-react-playground', defaultConfig); const [data, setData] = useState(null); function handleChange(e) { const { name, value, type, checked } = e.target; setConfig(prev => ({ ...prev, [name]: type === 'checkbox' ? checked : value })); } return (

Auth0 React

{ if (appState.connectedAccount) setData(appState.connectedAccount); window.history.replaceState({}, document.title, '/'); }} > 0) { // Show enrollment UI } else { // User has enrolled authenticators - get the list of enrolled authenticator const authenticators = await mfa.getAuthenticators(error.mfa_token); // proceed with challenge } } } ``` -------------------------------- ### Initialize Auth0Provider Source: https://context7.com/auth0/auth0-react/llms.txt Wrap your application with Auth0Provider and configure it with your Auth0 domain and client ID. Set up redirect URIs, audience, scopes, and token caching. The onRedirectCallback handles post-login redirects. ```jsx import React from 'react'; import { createRoot } from 'react-dom/client'; import { Auth0Provider } from '@auth0/auth0-react'; import App from './App'; const root = createRoot(document.getElementById('app')); root.render( { // Handle redirect after login window.history.replaceState( {}, document.title, appState?.returnTo || window.location.pathname ); }} > ); ``` -------------------------------- ### Error.captureStackTrace Example Source: https://github.com/auth0/auth0-react/blob/main/docs/classes/PopupCancelledError.html This example demonstrates how to use Error.captureStackTrace to create a .stack property on an object. The optional constructorOpt argument can be used to hide implementation details from the stack trace. ```typescript const myObject = {}; Error.captureStackTrace(myObject); myObject.stack; // Similar to `new Error().stack` ``` ```typescript function a() { b(); } function b() { c(); } function c() { // Create an error without stack trace to avoid calculating the stack trace twice. const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; const error = new Error(); Error.stackTraceLimit = stackTraceLimit; // Capture the stack trace above function b Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace throw error; } a(); ``` -------------------------------- ### MfaChallengeError Class Source: https://github.com/auth0/auth0-react/blob/main/docs/classes/MfaChallengeError.html Details about the MfaChallengeError class, including its constructor, properties, and an example of its usage in error handling. ```APIDOC ## MfaChallengeError Class Error thrown when initiating an MFA challenge fails. ### Description This class represents an error that occurs specifically during the initiation of a Multi-Factor Authentication (MFA) challenge. It extends the base `MfaError` class and provides specific details about the failure. ### Constructor * `new MfaChallengeError(error: string, error_description: string)` * **Parameters** * `error` (string) - The error code. * `error_description` (string) - A human-readable description of the error. * **Returns** MfaChallengeError ### Properties * **error** (string) - Inherited from `MfaError`. The error code. * **error_description** (string) - Inherited from `MfaError`. A description of the error. * **message** (string) - Inherited from `MfaError`. The error message. * **name** (string) - Inherited from `MfaError`. The name of the error type. * **stack** (string, optional) - Inherited from `MfaError`. The stack trace of the error. ### Example ```javascript try { const challenge = await mfa.challenge({ mfaToken: mfaToken, challengeType: 'otp', authenticatorId: 'otp|dev_123' }); } catch (error) { if (error instanceof MfaChallengeError) { console.log(error.error); // e.g., 'too_many_attempts' console.log(error.error_description); // e.g., 'Rate limit exceeded' } } ``` ``` -------------------------------- ### Initialize Auth0Provider Source: https://github.com/auth0/auth0-react/blob/main/docs/functions/Auth0Provider.html Wrap your application with Auth0Provider and configure it with your domain, client ID, and redirect URI. This makes authentication services available to all child components. ```jsx ``` -------------------------------- ### MfaEnrollmentError Class Source: https://github.com/auth0/auth0-react/blob/main/docs/classes/MfaEnrollmentError.html Details about the MfaEnrollmentError class, including its constructor, properties, and an example of its usage in error handling. ```APIDOC ## Class MfaEnrollmentError Error thrown when enrolling an MFA authenticator fails. ### Description This class represents an error that occurs specifically when the process of enrolling a Multi-Factor Authentication (MFA) authenticator fails. It inherits from `MfaError` and provides specific details about the enrollment failure. ### Constructor * `new MfaEnrollmentError(error: string, error_description: string)` * **Parameters** * `error` (string) - The error code. * `error_description` (string) - A human-readable description of the error. * **Returns** `MfaEnrollmentError` ### Properties * `error` (string) - The error code associated with the MFA enrollment failure. Inherited from `MfaError`. * `error_description` (string) - A detailed description of the MFA enrollment error. Inherited from `MfaError`. * `message` (string) - The error message. Inherited from `Error`. * `name` (string) - The name of the error, which is 'MfaEnrollmentError'. Inherited from `Error`. * `stack` (string, optional) - The stack trace of the error. Inherited from `Error`. ### Static Properties * `stackTraceLimit` (number) - Specifies the number of stack frames collected by a stack trace. Inherited from `Error`. ### Example ```javascript try { const enrollment = await mfa.enroll({ authenticator_types: ['otp'] }); } catch (error) { if (error instanceof MfaEnrollmentError) { console.log(error.error); // e.g., 'invalid_phone_number' console.log(error.error_description); // e.g., 'Invalid phone number format' } } ``` ``` -------------------------------- ### Connect Account with Redirect - Basic Usage Source: https://github.com/auth0/auth0-react/blob/main/docs/interfaces/RedirectConnectAccountOptions.html Use this to initiate the account connection flow with a specified connection. The `connection` parameter is required. ```javascript await auth0.connectAccountWithRedirect({ connection: 'google-oauth2'}); ``` -------------------------------- ### Configure Auth0Provider in Next.js Source: https://github.com/auth0/auth0-react/blob/main/EXAMPLES.md Wrap your root element with `Auth0Provider` to configure the SDK and set up the context for hooks. The `onRedirectCallback` handles redirection after login. ```jsx import React from 'react'; import App from 'next/app'; import Router from 'next/router'; import { Auth0Provider } from '@auth0/auth0-react'; const onRedirectCallback = (appState) => { // Use Next.js's Router.replace method to replace the url Router.replace(appState?.returnTo || '/'); }; class MyApp extends App { render() { const { Component, pageProps } = this.props; return ( ); } } export default MyApp; ``` -------------------------------- ### Get ID Token Claims Source: https://github.com/auth0/auth0-react/blob/main/docs/interfaces/Auth0ContextInterface.html Retrieves all claims from the ID token if available. Ensure the user is authenticated before calling this method. ```javascript const claims = await getIdTokenClaims(); ``` -------------------------------- ### getAccessTokenSilently Method Source: https://context7.com/auth0/auth0-react/llms.txt Retrieves an access token silently from the cache or by refreshing it. Use this to get tokens for calling protected APIs. ```APIDOC ## getAccessTokenSilently ### Description Retrieves an access token silently from the cache or by refreshing it. Use this to get tokens for calling protected APIs. Supports detailed response mode for token metadata. ### Usage Example ```jsx import React, { useEffect, useState } from 'react'; import { useAuth0 } from '@auth0/auth0-react'; function ApiCaller() { const { getAccessTokenSilently, isAuthenticated } = useAuth0(); const [data, setData] = useState(null); const [error, setError] = useState(null); useEffect(() => { const fetchData = async () => { if (!isAuthenticated) return; try { // Simple usage - returns token string const token = await getAccessTokenSilently({ authorizationParams: { audience: 'https://api.example.com/', scope: 'read:posts write:posts' } }); // Or with detailed response for token metadata const { access_token, id_token, expires_in, token_type } = await getAccessTokenSilently({ authorizationParams: { audience: 'https://api.example.com/' }, detailedResponse: true }); const response = await fetch('https://api.example.com/posts', { headers: { Authorization: `${token_type} ${access_token}` } }); if (!response.ok) throw new Error('API request failed'); setData(await response.json()); } catch (e) { setError(e.message); console.error('Token or API error:', e); } }; fetchData(); }, [getAccessTokenSilently, isAuthenticated]); if (error) return
Error: {error}
; if (!data) return
Loading...
; return
{JSON.stringify(data, null, 2)}
; } export default ApiCaller; ``` ``` -------------------------------- ### Accessing ConnectAccountRedirectResult Properties Source: https://github.com/auth0/auth0-react/blob/main/docs/types/ConnectAccountRedirectResult.html Example demonstrating how to access the appState and response_type properties from the result of auth0.connectAccountWithRedirect. Ensure the connection is successful before accessing these properties. ```javascript const result = await auth0.connectAccountWithRedirect(options); console.log(result.appState); // Access persisted app state console.log(result.connection); // The connection of the account you connected to. console.log(result.response_type === 'connect_code'); // The response type will be 'connect_code' ``` -------------------------------- ### Handle MFA Enrollment and Challenge Source: https://github.com/auth0/auth0-react/blob/main/docs/interfaces/Auth0ContextInterface.html This code demonstrates how to handle an MFA required error, check for enrollment factors, enroll in OTP, and then challenge the user for verification. It requires the use of `useAuth0` and `getAccessTokenSilently`. ```javascript const { mfa, getAccessTokenSilently } = useAuth0();try { await getAccessTokenSilently();} catch (error) { if (error.error === 'mfa_required') { // Check if enrollment is needed const factors = await mfa.getEnrollmentFactors(error.mfa_token); if (factors.length > 0) { // Enroll in OTP const enrollment = await mfa.enroll({ mfaToken: error.mfa_token, factorType: 'otp' }); console.log('QR Code:', enrollment.barcodeUri); } // Get authenticators and challenge const authenticators = await mfa.getAuthenticators(error.mfa_token); await mfa.challenge({ mfaToken: error.mfa_token, challengeType: 'otp', authenticatorId: authenticators[0].id }); // Verify with user's code const tokens = await mfa.verify({ mfaToken: error.mfa_token, otp: userCode }); } } ``` -------------------------------- ### Auth0 Configuration (.env file) Source: https://github.com/auth0/auth0-react/blob/main/examples/cra-react-router/README.md Configure your Auth0 domain, client ID, and API audience in the .env file. Set SKIP_PREFLIGHT_CHECK to true to workaround potential issues with nested create-react-app projects. ```dotenv REACT_APP_DOMAIN=your_domain REACT_APP_CLIENT_ID=your_client_id REACT_APP_AUDIENCE=your_audience SKIP_PREFLIGHT_CHECK=true ``` -------------------------------- ### getConfiguration Source: https://github.com/auth0/auth0-react/blob/main/docs/interfaces/Auth0ContextInterface.html Retrieves a readonly copy of the SDK's initialization configuration, including the domain and client ID. ```APIDOC ## GET /configuration ### Description Retrieves a readonly copy of the SDK's initialization configuration, including the domain and client ID. ### Method GET ### Endpoint N/A (Client-side method) ### Parameters None ### Request Example ```javascript const config = getConfiguration(); ``` ### Response #### Success Response (200) - **ClientConfiguration** - An object containing the domain and clientId. #### Response Example ```json { "domain": "tenant.auth0.com", "clientId": "abc123" } ``` ``` -------------------------------- ### Get Enrolled MFA Authenticators Source: https://github.com/auth0/auth0-react/blob/main/docs/interfaces/MfaApiClient.html Retrieves a list of MFA authenticators enrolled for the user, filtered by challenge types from the current MFA context. ```APIDOC ## GET /api/mfa/authenticators ### Description Gets enrolled MFA authenticators filtered by challenge types from context. Challenge types are automatically resolved from the stored MFA context (set when mfa_required error occurred). ### Method GET ### Endpoint /api/mfa/authenticators ### Parameters #### Query Parameters - **mfaToken** (string) - Required - MFA token from the `mfa_required` error. ### Response #### Success Response (200) - **authenticators** (array) - An array of enrolled authenticator objects. - **authenticator** (object) - Details of an enrolled authenticator. - **id** (string) - The unique identifier of the authenticator. - **type** (string) - The type of the authenticator (e.g., 'otp', 'sms', 'push-notification'). - **displayName** (string) - A user-friendly name for the authenticator. #### Response Example ```json [ { "id": "authenticator_id_1", "type": "otp", "displayName": "Google Authenticator" }, { "id": "authenticator_id_2", "type": "sms", "displayName": "+12025551234" } ] ``` ### Throws If the request fails or MFA context is not found. ``` -------------------------------- ### Manual DPoP Handling with getAccessTokenSilently Source: https://context7.com/auth0/auth0-react/llms.txt Manually handle DPoP by obtaining an access token and generating a DPoP proof using `generateDpopProof`. Remember to manage the DPoP nonce for subsequent requests. ```jsx // Manual DPoP handling (advanced) const { getAccessTokenSilently, generateDpopProof, getDpopNonce, setDpopNonce } = useAuth0(); const callApiManually = async () => { const { access_token, token_type } = await getAccessTokenSilently({ detailedResponse: true }); if (token_type === 'DPoP') { // Generate DPoP proof for this specific request const dpopProof = await generateDpopProof({ httpMethod: 'GET', httpUri: 'https://api.example.com/resource', nonce: getDpopNonce('api') // Use stored nonce if available }); const response = await fetch('https://api.example.com/resource', { headers: { 'Authorization': `DPoP ${access_token}`, 'DPoP': dpopProof } }); // Store nonce from response for next request const newNonce = response.headers.get('DPoP-Nonce'); if (newNonce) setDpopNonce(newNonce, 'api'); return response.json(); } } ``` -------------------------------- ### Run Unit Tests Source: https://github.com/auth0/auth0-react/blob/main/CONTRIBUTING.md Execute the unit tests for the Auth0 React SDK using the npm test command. This command utilizes Jest for running the tests. ```bash npm test ``` -------------------------------- ### MFA Client - Get Authenticators Source: https://github.com/auth0/auth0-react/blob/main/docs/interfaces/Auth0ContextInterface.html Retrieves a list of enrolled Multi-Factor Authentication authenticators for a given MFA token. This is part of the MFA API client. ```javascript const { mfa } = useAuth0(); const authenticators = await mfa.getAuthenticators(mfaToken); ``` -------------------------------- ### Login with Redirect Source: https://github.com/auth0/auth0-react/blob/main/docs/interfaces/Auth0ContextInterface.html Initiates an authentication flow by redirecting the user to the Auth0 `/authorize` endpoint. ```APIDOC ## POST /authorize (Login with Redirect) ### Description Redirects the user to the Auth0 `/authorize` endpoint to perform authentication. Secure `state` and `nonce` parameters are generated automatically. ### Method POST ### Endpoint /authorize ### Parameters #### Query Parameters - **options** (RedirectLoginOptions) - Optional - Options for the redirect login, including `AppState`. ### Request Example ```javascript await loginWithRedirect(options); ``` ### Response #### Success Response (void) This method does not return a value upon successful authentication; the user is redirected to the Auth0 authorization server. #### Response Example (No response body on success, user is redirected) ``` -------------------------------- ### Create Auth0Client Instance Source: https://github.com/auth0/auth0-react/blob/main/EXAMPLES.md Instantiate Auth0Client for use outside the React component tree. Ensure you replace 'YOUR_AUTH0_DOMAIN' and 'YOUR_AUTH0_CLIENT_ID' with your actual Auth0 credentials. ```jsx import { Auth0Client } from '@auth0/auth0-spa-js'; export const auth0Client = new Auth0Client({ domain: 'YOUR_AUTH0_DOMAIN', clientId: 'YOUR_AUTH0_CLIENT_ID', authorizationParams: { redirect_uri: window.location.origin, }, }); ``` -------------------------------- ### Home Page Component with Login Source: https://context7.com/auth0/auth0-react/llms.txt A basic Home component that displays a welcome message for authenticated users or a login button using `loginWithRedirect`. ```jsx // Page components const Home = () => { const { loginWithRedirect, isAuthenticated, user } = useAuth0(); return (

Home

{isAuthenticated ? (

Welcome, {user.name}!

) : ( )}
); }; ``` -------------------------------- ### Get DPoP Nonce Source: https://github.com/auth0/auth0-react/blob/main/docs/interfaces/Auth0ContextInterface.html Retrieves the current DPoP nonce for making requests to Auth0. Requires Auth0ClientOptions.useDpop to be enabled. May return undefined if not yet populated. ```typescript getDpopNonce: (id?: string) => Promise ``` -------------------------------- ### Connect Account with Redirect - With Redirect URI Source: https://github.com/auth0/auth0-react/blob/main/docs/interfaces/RedirectConnectAccountOptions.html Specify the URI to redirect back to after the account connection is complete using the `redirectUri` parameter. ```javascript await auth0.connectAccountWithRedirect({ connection: 'google-oauth2', redirectUri: 'https://myapp.com/callback' }); ``` -------------------------------- ### Prepare Stack Trace Source: https://github.com/auth0/auth0-react/blob/main/docs/classes/MfaVerifyError.html Allows for customization of how stack traces are formatted. This method is part of the V8 stack trace API. ```APIDOC ## Static prepareStackTrace ### Description Customizes the formatting of stack traces. ### Method `static` ### Parameters * **err** (Error) - Required - The error object. * **stackTraces** (CallSite[]) - Required - An array of CallSite objects representing the stack trace. ### Returns any - The formatted stack trace. ### See [https://v8.dev/docs/stack-trace-api#customizing-stack-traces](https://v8.dev/docs/stack-trace-api#customizing-stack-traces) ### Example ```javascript // Example usage would involve setting Error.prepareStackTrace // and then capturing a stack trace. Error.prepareStackTrace = function (err, stackTraces) { // Custom formatting logic here return stackTraces.map(st => st.getFileName() + ':' + st.getLineNumber()).join('\n'); }; const error = new Error(); console.log(error.stack); ``` ``` -------------------------------- ### Configure Auth0Provider for React 18+ Source: https://github.com/auth0/auth0-react/blob/main/docs/index.html Wrap your application with Auth0Provider and provide your Auth0 domain and client ID. Ensure the redirect_uri is correctly set. ```javascript import React from 'react'; import { createRoot } from 'react-dom/client'; import { Auth0Provider } from '@auth0/auth0-react'; import App from './App'; const root = createRoot(document.getElementById('app')); root.render( ); ``` -------------------------------- ### Get Access Token Silently with MFA Handling Source: https://github.com/auth0/auth0-react/blob/main/EXAMPLES.md Use `getAccessTokenSilently` to fetch tokens. If MFA is required, it automatically opens a popup for the user to complete the process, then returns the token. ```jsx import React, { useEffect, useState } from 'react'; import { useAuth0 } from '@auth0/auth0-react'; const ProtectedResource = () => { const { getAccessTokenSilently } = useAuth0(); const [data, setData] = useState(null); useEffect(() => { (async () => { try { // If MFA is required, a popup opens automatically. // The token is returned after the user completes MFA. const token = await getAccessTokenSilently({ authorizationParams: { audience: 'https://api.example.com/', scope: 'read:sensitive', }, }); const response = await fetch('https://api.example.com/sensitive', { headers: { Authorization: `Bearer ${token}` }, }); setData(await response.json()); } catch (e) { console.error(e); } })(); }, [getAccessTokenSilently]); if (!data) return
Loading...
; return
{JSON.stringify(data)}
; }; export default ProtectedResource; ``` -------------------------------- ### Get Available MFA Enrollment Factors Source: https://github.com/auth0/auth0-react/blob/main/docs/interfaces/MfaApiClient.html Retrieves the available MFA enrollment factors based on the user's context. This method exposes enrollment options from the `mfa_required` error. ```APIDOC ## GET /api/mfa/enrollment-factors ### Description Gets available MFA enrollment factors from the stored context. This method exposes the enrollment options from the `mfa_required` error's `mfaRequirements.enroll` array. ### Method GET ### Endpoint /api/mfa/enrollment-factors ### Parameters #### Query Parameters - **mfaToken** (string) - Required - MFA token from the `mfa_required` error. ### Response #### Success Response (200) - **enrollmentFactors** (array) - An array of available enrollment factors. - **factor** (object) - Details of an available enrollment factor. - **type** (string) - The type of the enrollment factor (e.g., 'otp', 'phone', 'push-notification'). #### Response Example ```json [ { "type": "otp" }, { "type": "phone" }, { "type": "push-notification" } ] ``` ### Throws If MFA context is not found. ``` -------------------------------- ### Auth0Provider Configuration Source: https://context7.com/auth0/auth0-react/llms.txt The main context provider component that wraps your application and provides authentication state and methods to all child components. Configure it with your Auth0 domain and client ID to initialize the SDK. ```APIDOC ## Auth0Provider ### Description The main context provider component that wraps your application and provides authentication state and methods to all child components. Configure it with your Auth0 domain and client ID to initialize the SDK. ### Usage Example ```jsx import React from 'react'; import { createRoot } from 'react-dom/client'; import { Auth0Provider } from '@auth0/auth0-react'; import App from './App'; const root = createRoot(document.getElementById('app')); root.render( { // Handle redirect after login window.history.replaceState( {}, document.title, appState?.returnTo || window.location.pathname ); }} > ); ``` ``` -------------------------------- ### Example Subject Token Type Source: https://github.com/auth0/auth0-react/blob/main/docs/types/CustomTokenExchangeOptions.html Specifies the type identifier for the subject token being exchanged. This must be a namespaced URI under your organization's control and cannot use Auth0 or IETF reserved patterns. ```string "urn:acme:legacy-system-token" ``` ```string "https://api.yourcompany.com/token-type/v1" ``` -------------------------------- ### prepareStackTrace - Customize Stack Traces Source: https://github.com/auth0/auth0-react/blob/main/docs/classes/PopupTimeoutError.html The `prepareStackTrace` static method allows for customization of error stack traces, as defined by the V8 V8 Stack Trace API. ```APIDOC ## Static prepareStackTrace ### Description Customizes the format of error stack traces. ### Method `static prepareStackTrace(err: Error, stackTraces: CallSite[]): any[]` ### Parameters - **err** (Error) - The error object. - **stackTraces** (CallSite[]) - An array of CallSite objects representing the stack trace. ### Returns `any[]` - The formatted stack trace. ### See [https://v8.dev/docs/stack-trace-api#customizing-stack-traces](https://v8.dev/docs/stack-trace-api#customizing-stack-traces) ### Note This method inherits from `TimeoutError.prepareStackTrace`. ```