1Auth0 Project Setup
- Create an account at auth0.com
- Create a Tenant (e.g., my-app.auth0.com)
- Applications → Create Application
- Select Single Page Web Applications
- Configure the following in Settings:
- Allowed Callback URLs:
http://localhost:5173 - Allowed Logout URLs:
http://localhost:5173 - Allowed Web Origins:
http://localhost:5173
- Allowed Callback URLs:
2React App Integration
Terminal
npm install @auth0/auth0-reactEnvironment Variables
.env.local
# .env.local
VITE_AUTH0_DOMAIN=your-tenant.auth0.com
VITE_AUTH0_CLIENT_ID=your-client-id
VITE_AUTH0_AUDIENCE=https://your-api-identifierAuth0Provider Setup
main.tsx
// main.tsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import { Auth0Provider } from '@auth0/auth0-react';
import App from './App';
import './index.css';
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<Auth0Provider
domain={import.meta.env.VITE_AUTH0_DOMAIN}
clientId={import.meta.env.VITE_AUTH0_CLIENT_ID}
authorizationParams={{
redirect_uri: window.location.origin,
audience: import.meta.env.VITE_AUTH0_AUDIENCE,
scope: 'openid profile email',
}}
>
<App />
</Auth0Provider>
</React.StrictMode>
);3Using the useAuth0 Hook
components/AuthButtons.tsx
// components/AuthButtons.tsx
import { useAuth0 } from '@auth0/auth0-react';
export function AuthButtons() {
const {
isAuthenticated,
isLoading,
user,
loginWithRedirect,
logout,
} = useAuth0();
if (isLoading) {
return <div>Loading...</div>;
}
if (isAuthenticated) {
return (
<div className="flex items-center gap-4">
<img
src={user?.picture}
alt={user?.name}
className="w-10 h-10 rounded-full"
/>
<span>{user?.name}</span>
<button
onClick={() => logout({ logoutParams: { returnTo: window.location.origin } })}
className="px-4 py-2 bg-red-600 text-white rounded-lg"
>
Sign Out
</button>
</div>
);
}
return (
<button
onClick={() => loginWithRedirect()}
className="px-4 py-2 bg-blue-600 text-white rounded-lg"
>
Sign In
</button>
);
}Key Properties/Methods
isAuthenticated- Whether user is logged inisLoading- Auth state loadinguser- User profile infologinWithRedirect()- Redirect to login pagelogout()- Sign outgetAccessTokenSilently()- Obtain API token
4Protected Route Implementation
components/ProtectedRoute.tsx
// components/ProtectedRoute.tsx
import { useAuth0, withAuthenticationRequired } from '@auth0/auth0-react';
// Method 1: Using HOC
export const ProtectedPage = withAuthenticationRequired(
function Dashboard() {
const { user } = useAuth0();
return <div>Welcome, {user?.name}!</div>;
},
{
onRedirecting: () => <div>Redirecting...</div>,
}
);
// Method 2: Direct check with hook
export function ProtectedContent({ children }: { children: React.ReactNode }) {
const { isAuthenticated, isLoading, loginWithRedirect } = useAuth0();
if (isLoading) return <div>Loading...</div>;
if (!isAuthenticated) {
loginWithRedirect();
return <div>Redirecting to login...</div>;
}
return <>{children}</>;
}5Backend API Integration
You need to include the Access Token when making API calls.
hooks/useApi.ts
// hooks/useApi.ts
import { useAuth0 } from '@auth0/auth0-react';
export function useApi() {
const { getAccessTokenSilently } = useAuth0();
const fetchWithToken = async (url: string, options: RequestInit = {}) => {
const token = await getAccessTokenSilently({
authorizationParams: {
audience: import.meta.env.VITE_AUTH0_AUDIENCE,
},
});
return fetch(url, {
...options,
headers: {
...options.headers,
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
},
});
};
return { fetchWithToken };
}
// Usage example
function ProjectList() {
const { fetchWithToken } = useApi();
const [projects, setProjects] = useState([]);
useEffect(() => {
fetchWithToken('/api/projects')
.then(res => res.json())
.then(data => setProjects(data));
}, []);
return <ul>{projects.map(p => <li key={p.id}>{p.name}</li>)}</ul>;
}Token Verification on Backend
server.js
// Backend (Node.js/Express example)
import { expressjwt } from 'express-jwt';
import jwksRsa from 'jwks-rsa';
const checkJwt = expressjwt({
secret: jwksRsa.expressJwtSecret({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 5,
jwksUri: `https://${process.env.AUTH0_DOMAIN}/.well-known/jwks.json`,
}),
audience: process.env.AUTH0_AUDIENCE,
issuer: `https://${process.env.AUTH0_DOMAIN}/`,
algorithms: ['RS256'],
});
// Protected API endpoint
app.get('/api/protected', checkJwt, (req, res) => {
// Token info is available in req.auth
res.json({ userId: req.auth.sub });
});6Role-Based Access Control (RBAC)
Auth0's RBAC feature lets you manage permissions per user.
RBAC Setup
// After creating roles in the Auth0 dashboard,
// add a Rule to include role info in tokens
// Auth0 Rule (configure in Actions or Rules)
exports.onExecutePostLogin = async (event, api) => {
const namespace = 'https://your-app.com';
if (event.authorization) {
api.idToken.setCustomClaim(`${namespace}/roles`, event.authorization.roles);
api.accessToken.setCustomClaim(`${namespace}/roles`, event.authorization.roles);
}
};
// Check roles in React
function AdminPanel() {
const { user, isAuthenticated } = useAuth0();
const roles = user?.['https://your-app.com/roles'] || [];
const isAdmin = roles.includes('admin');
if (!isAdmin) {
return <div>Admin permission required.</div>;
}
return <div>Admin Panel</div>;
}Info
You can create roles and assign them to users in the Auth0 dashboard under User Management → Roles.