Skip to main content

Use AI to integrate Auth0

If you use an AI coding assistant like Claude Code, Cursor, or GitHub Copilot, you can add Auth0 authentication automatically in minutes using agent skills.Install:
npx skills add auth0/agent-skills
Then ask your AI assistant:
Add Auth0 authentication to my React app
Your AI assistant will automatically create your Auth0 application, fetch credentials, install @auth0/auth0-react, create authentication components, and set up your configuration. Full agent skills documentation →
Prerequisites: Before you begin, ensure you have the following installed:React Version Compatibility: This quickstart works with React 18.x and newer.

Get Started

This quickstart demonstrates how to add Auth0 authentication to a React application. You’ll build a secure single-page app with login, logout, and user profile features using the Auth0 React SDK.
1

Create a new project

Create a new React project for this Quickstart
npm create vite@latest auth0-react -- --template react-ts
Open the project
cd auth0-react
2

Install the Auth0 React SDK

npm add @auth0/auth0-react && npm install
3

Setup your Auth0 App

Next up, you need to create a new app on your Auth0 tenant and add the environment variables to your project.You have three options to set up your Auth0 app: use the Quick Setup tool (recommended), run a CLI command, or configure manually via the Dashboard:
4

Add the provider

src/main.tsx
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import './index.css'; // Importing the main CSS file
import App from './App.tsx';
import { Auth0Provider } from '@auth0/auth0-react';

createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <Auth0Provider
      domain={import.meta.env.VITE_AUTH0_DOMAIN}
      clientId={import.meta.env.VITE_AUTH0_CLIENT_ID}
      authorizationParams={{
        redirect_uri: window.location.origin
      }}
    >
      <App />
    </Auth0Provider>
  </StrictMode>
);
5

Create Login, Logout and Profile Components

Create files
touch src/LoginButton.tsx && touch src/LogoutButton.tsx && touch src/Profile.tsx
And add the following code snippets
7

Run your app

npm run dev
CheckpointYou should now have a fully functional Auth0 login page running on your localhost

Advanced Usage

Use Auth0’s authentication state to protect specific routes in your application:
src/App.jsx
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
import { useAuth0 } from '@auth0/auth0-react';
import Profile from './components/Profile';
import Dashboard from './components/Dashboard';
import LoginButton from './components/LoginButton';

function ProtectedRoute({ children }) {
  const { isAuthenticated, isLoading } = useAuth0();
  
  if (isLoading) return <div>Loading...</div>;
  
  return isAuthenticated ? children : <Navigate to="/" />;
}

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<LoginButton />} />
        <Route 
          path="/profile" 
          element={
            <ProtectedRoute>
              <Profile />
            </ProtectedRoute>
          } 
        />
        <Route 
          path="/dashboard" 
          element={
            <ProtectedRoute>
              <Dashboard />
            </ProtectedRoute>
          } 
        />
      </Routes>
    </BrowserRouter>
  );
}
Configure your Auth0Provider to include an API audience and use the getAccessTokenSilently method:
src/main.jsx
import { Auth0Provider } from '@auth0/auth0-react';

const root = ReactDOM.createRoot(document.getElementById('root'));

root.render(
  <Auth0Provider
    domain={import.meta.env.VITE_AUTH0_DOMAIN}
    clientId={import.meta.env.VITE_AUTH0_CLIENT_ID}
    authorizationParams={{
      redirect_uri: window.location.origin,
      audience: "YOUR_API_IDENTIFIER"
    }}
  >
    <App />
  </Auth0Provider>
);
Then make authenticated API calls:
src/components/ApiCall.jsx
import { useState } from 'react';
import { useAuth0 } from '@auth0/auth0-react';

function ApiCall() {
  const { getAccessTokenSilently } = useAuth0();
  const [apiResponse, setApiResponse] = useState(null);

  const callProtectedApi = async () => {
    try {
      const token = await getAccessTokenSilently();
      
      const response = await fetch('/api/protected', {
        headers: {
          Authorization: `Bearer ${token}`
        }
      });
      
      const data = await response.json();
      setApiResponse(data);
    } catch (error) {
      console.error('API call failed:', error);
    }
  };

  return (
    <div>
      <button onClick={callProtectedApi}>Call API</button>
      {apiResponse && <pre>{JSON.stringify(apiResponse, null, 2)}</pre>}
    </div>
  );
}

export default ApiCall;
Create reusable custom hooks for common authentication patterns:
src/hooks/useAuthenticatedUser.js
import { useAuth0 } from '@auth0/auth0-react';
import { useEffect, useState } from 'react';

export function useAuthenticatedUser() {
  const { user, isAuthenticated, isLoading, getAccessTokenSilently } = useAuth0();
  const [accessToken, setAccessToken] = useState(null);

  useEffect(() => {
    if (isAuthenticated && !isLoading) {
      getAccessTokenSilently()
        .then(token => setAccessToken(token))
        .catch(console.error);
    }
  }, [isAuthenticated, isLoading, getAccessTokenSilently]);

  return {
    user,
    accessToken,
    isAuthenticated,
    isLoading
  };
}
Usage in components:
src/components/UserDashboard.jsx
import { useAuthenticatedUser } from '../hooks/useAuthenticatedUser';

function UserDashboard() {
  const { user, accessToken, isLoading } = useAuthenticatedUser();

  if (isLoading) return <div>Loading...</div>;

  return (
    <div>
      <h1>Welcome, {user?.name}</h1>
      <p>Access Token: {accessToken ? 'Available' : 'Not available'}</p>
    </div>
  );
}