Skip to content

Auth0 React Integration — Add Authentication to React Applications

DodaTech Updated 2026-06-28 5 min read

In this tutorial, you will learn about Auth0 React Integration. We cover key concepts, practical examples, and best practices to help you master this topic.

The Auth0 React SDK (@auth0/auth0-react) provides React components and hooks for adding authentication to single-page applications, with built-in route protection, user profile access, and token management.

What You'll Learn

By the end of this lesson you will install and configure the Auth0 React SDK, wrap your app with Auth0Provider, protect routes with authentication guards, access user data with hooks, and call APIs with access tokens.

Why It Matters

SPAs face unique authentication challenges -- tokens in the browser, redirect flows, and session persistence. The Auth0 React SDK handles these challenges with React-idiomatic patterns.

Real-World Use

DodaZIP's React dashboard uses the Auth0 React SDK. The Auth0Provider wraps the entire app, protected routes use the withAuthenticationRequired HOC, and API calls include the access token from the useAuth0 hook.

flowchart LR
    A[React App] -->|Auth0Provider| P[Auth Context]
    P -->|useAuth0| L[Login Button]
    P -->|withAuthRequired| R[Protected Route]
    P -->|getAccessTokenSilently| C[API Client]
    C -->|API Call + Token| API[Backend]
    style A fill:#eb5424,color:#fff

Installing the SDK

Install the Auth0 React SDK.

# Install the SDK
npm install @auth0/auth0-react

# If you need to call APIs, also install
npm install axios
# sdk_setup.py
# SDK setup requirements

def sdk_requirements():
    print("Auth0 React SDK Requirements:")
    print()
    print("Environment variables needed:")
    print("  REACT_APP_AUTH0_DOMAIN: Your Auth0 tenant domain")
    print("  REACT_APP_AUTH0_CLIENT_ID: Your application client ID")
    print("  REACT_APP_AUTH0_AUDIENCE: Your API identifier")
    print()
    print("Auth0 Application configuration:")
    print("  - Type: Single Page Application")
    print("  - Allowed Callback URLs: http://localhost:3000")
    print("  - Allowed Logout URLs: http://localhost:3000")
    print("  - Allowed Web Origins: http://localhost:3000")

sdk_requirements()

Configuring Auth0Provider

Wrap your application with the Auth0Provider.

// App.js
import React from 'react';
import { Auth0Provider } from '@auth0/auth0-react';
import { BrowserRouter } from 'react-router-dom';
import MainApp from './MainApp';

const App = () => {
  return (
    <BrowserRouter>
      <Auth0Provider
        domain={process.env.REACT_APP_AUTH0_DOMAIN}
        clientId={process.env.REACT_APP_AUTH0_CLIENT_ID}
        authorizationParams={{
          redirect_uri: window.location.origin,
          audience: process.env.REACT_APP_AUTH0_AUDIENCE,
          scope: "openid profile email"
        }}
        cacheLocation="localstorage"
      >
        <MainApp />
      </Auth0Provider>
    </BrowserRouter>
  );
};

export default App;
# provider_config.py
# Understanding Auth0Provider configuration

def provider_options():
    print("Auth0Provider Configuration Options:")
    print()
    print("Required:")
    print("  domain: Your Auth0 tenant domain")
    print("  clientId: Your application's client ID")
    print()
    print("Authorization params (recommended):")
    print("  redirect_uri: Where Auth0 redirects after login")
    print("  audience: Your API identifier")
    print("  scope: Requested scopes (openid profile email)")
    print()
    print("Optional settings:")
    print("  cacheLocation: 'localstorage' or 'memory'")
    print("  useRefreshTokens: Enable refresh token rotation")
    print("  onRedirectCallback: Custom post-login redirect")

provider_options()

Using Auth0 Hooks

Access authentication state with React hooks.

// Profile.js
import React from 'react';
import { useAuth0 } from '@auth0/auth0-react';

const Profile = () => {
  const { user, isAuthenticated, isLoading, loginWithRedirect, logout } = useAuth0();
  
  if (isLoading) {
    return <div>Loading...</div>;
  }
  
  if (!isAuthenticated) {
    return <button onClick={() => loginWithRedirect()}>Log In</button>;
  }
  
  return (
    <div>
      <img src={user.picture} alt={user.name} />
      <h2>{user.name}</h2>
      <p>{user.email}</p>
      <button onClick={() => logout({ logoutParams: { returnTo: window.location.origin } })}>
        Log Out
      </button>
    </div>
  );
};

export default Profile;
# react_hooks.py
# Available Auth0 React hooks

def auth_hooks():
    hooks = {
        "useAuth0()": "Main hook returning auth state and methods",
        "  - user": "User profile object (when authenticated)",
        "  - isAuthenticated": "Boolean indicating auth status",
        "  - isLoading": "True during initial auth check",
        "  - error": "Auth error object",
        "  - loginWithRedirect()": "Redirect to Universal Login",
        "  - logout()": "Log out the user",
        "  - getAccessTokenSilently()": "Get token without user prompt",
        "  - getAccessTokenWithPopup()": "Get token via popup",
    }
    
    print("Auth0 React Hooks:")
    for hook, desc in hooks.items():
        print(f"  {hook:35s} {desc}")

auth_hooks()

Protecting Routes

Guard routes with authentication requirements.

// ProtectedRoute.js
import React from 'react';
import { withAuthenticationRequired } from '@auth0/auth0-react';

const Dashboard = () => {
  return (
    <div>
      <h1>Protected Dashboard</h1>
      <p>This page requires authentication.</p>
    </div>
  );
};

// Option 1: Higher-order component
export default withAuthenticationRequired(Dashboard, {
  onRedirecting: () => <div>Redirecting to login...</div>,
});

// Option 2: With NavigationGuard component
// <Route path="/dashboard" element={<ProtectedRoute />} />
# route_protection.py
# Route protection strategies

def route_protection():
    print("Route Protection Strategies:")
    print()
    print("1. withAuthenticationRequired HOC")
    print("   - Wraps component, redirects to login if unauthenticated")
    print()
    print("2. Custom ProtectedRoute component")
    print("   - Renders children if authenticated, redirects otherwise")
    print()
    print("3. Per-component check")
    print("   - Use isAuthenticated from useAuth0() in each component")
    print()
    print("Loading state:")
    print("   - Show loading spinner during auth check")
    print("   - Use onRedirecting prop for custom loading UI")

route_protection()

Common Mistakes

  1. Missing cacheLocation setting: Default Caching is in-memory, which is cleared on page refresh. Set cacheLocation: 'localstorage' for persistent sessions.

  2. Not handling the loading state: The SDK starts with isLoading=true. Not showing a loading state results in a flash of unauthenticated content.

  3. Calling getAccessTokenSilently without await: The method returns a Promise. Forgetting await returns a Promise object instead of the token.

  4. Incorrect redirect URI: The redirect URI must exactly match one of the Allowed Callback URLs in the Auth0 application settings.

  5. Not scoping tokens for the API: Without the audience parameter, the access token cannot be used to call your custom API.

Practice Questions

  1. What component wraps the application to provide Auth0 context? Auth0Provider, which must be placed at the root of the component tree.

  2. What hook provides authentication state and methods? useAuth0(), which returns user, isAuthenticated, isLoading, loginWithRedirect, logout, and more.

  3. How do you protect a route from unauthenticated access? Use the withAuthenticationRequired higher-order component or custom route guards.

  4. How do you get an access token for API calls? Use getAccessTokenSilently() to retrieve the token without user interaction.

  5. Challenge: Build a complete React application with login, protected routes, user profile display, and API calls using the Auth0 React SDK.

FAQ

Does the Auth0 React SDK support Next.js?

Next.js has its own SDK: @auth0/nextjs-auth0. The React SDK is for client-side SPAs.

How do I handle token refresh in React?

Set useRefreshTokens: true in Auth0Provider. The SDK handles automatic refresh.

Can I use TypeScript with the Auth0 React SDK?

Yes. The SDK includes TypeScript definitions.

How do I customize the login page?

Configure Universal Login in the Auth0 Dashboard, not from the React SDK.

What happens on page refresh?

The SDK checks the auth state on mount. With localstorage caching, the session persists across refreshes.

Mini Project

Create a complete React application with authentication including: Auth0Provider configuration, login/logout buttons, protected dashboard, user profile page, and an API call component that uses the access token.

def react_auth_project():
    print("React Auth Application Structure:")
    print()
    print("src/")
    print("  App.js")
    print("    - BrowserRouter > Auth0Provider > Routes")
    print("  components/")
    print("    LoginButton.js       - loginWithRedirect()")
    print("    LogoutButton.js      - logout()")
    print("    Profile.js           - useAuth0() -> user")
    print("    ProtectedRoute.js    - withAuthenticationRequired")
    print("  pages/")
    print("    Home.js              - Public page")
    print("    Dashboard.js         - Protected page")
    print("    Admin.js             - Protected + role check")
    print("  services/")
    print("    api.js               - getAccessTokenSilently + fetch")

react_auth_project()

What's Next

Next: Auth0 Security for securing your Auth0 configuration.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro