Configure React frontend with django-allauth headless API integration, including authentication UI, auth state management, protected routes, and social authentication flows
Configures a React frontend to integrate with django-allauth's headless API for complete authentication. This skill is triggered when you need to set up authentication UI, state management, and protected routes for a React app that uses a Django backend with django-allauth.
/plugin marketplace add otoshek/Claude-Code-Toolkit/plugin install claude-code-toolkit@claude-code-toolkitThis skill inherits all available tools. When active, it can use any tool Claude has access to.
README.mdreferences/styling-guide.mdscripts/test_auth_flows.pyConfigure a React frontend application to integrate with django-allauth's headless API, enabling complete authentication workflows including signup, login, email verification, password reset, and social authentication. This skill handles the entire setup process from copying authentication modules to validating flows with automated testing.
Before starting this configuration, ensure the following requirements are met:
react-router-dom for routingAPI_BASE_URL constant exported from a config file (typically src/config/api.js or src/config/api.jsx)frontend/src/ with standard Vite directory structureClone the django-allauth repository at the project root:
git clone https://github.com/pennersr/django-allauth
Refactor authentication components by renaming .js files to .jsx:
find django-allauth/examples/react-spa/frontend/src/ -name "*.js" -exec bash -c 'mv "$0" "${0%.js}.jsx"' {} \;
Copy the authentication modules into the React project:
mkdir -p frontend/src/user_management
find django-allauth/examples/react-spa/frontend/src/ -mindepth 1 -maxdepth 1 -type d -exec cp -r {} frontend/src/user_management/ \;
This creates a user_management directory in the React project and copies all authentication-related folders from the cloned repository. The django-allauth/ directory remains available for later steps in this skill.
Install the WebAuthn dependency required by the authentication modules:
npm --prefix ./frontend install @github/webauthn-json
File: frontend/src/App.jsx
Import the AuthContextProvider and wrap the app's content with it:
import { AuthContextProvider } from './user_management/auth'
Wrap the existing app content (typically the router) with <AuthContextProvider>:
<AuthContextProvider>
{/* Existing app content */}
</AuthContextProvider>
File: frontend/src/user_management/lib/allauth.jsx
After the getCSRFToken import, add:
import { API_BASE_URL } from '../../config/api'
Then update the API endpoint path from:
`/_allauth/${Client.BROWSER}/v1`
To:
`${API_BASE_URL}/_allauth/${Client.BROWSER}/v1`
Update redirect paths from /calculator to /dashboard:
File: frontend/src/user_management/auth/routing.jsx
Change the LOGIN_REDIRECT_URL path to:
LOGIN_REDIRECT_URL: '/'
File: frontend/src/user_management/account/ChangePassword.jsx
Replace any occurrence of '/calculator' with '/dashboard'
Copy the authentication router file and clean up the cloned repository:
cp django-allauth/examples/react-spa/frontend/src/Router.jsx frontend/src/router/AuthRouter.jsx && rm -rf django-allauth
File: frontend/src/router/AuthRouter.jsx
Update all import paths to use the user_management directory:
Change:
import { AuthChangeRedirector, AnonymousRoute, AuthenticatedRoute } from './auth'
To:
import { AuthChangeRedirector, AnonymousRoute, AuthenticatedRoute } from '../user_management/auth'
Update all component imports (like Login, Signup, ChangeEmail, etc.) from relative paths to use user_management:
Change:
import Login from './account/Login'
import Signup from './account/Signup'
// ... etc
To:
import Login from '../user_management/account/Login'
import Signup from '../user_management/account/Signup'
// ... etc
Update the Root import:
import Root from '../layouts/Root'
Update the useConfig import:
import { useConfig } from '../user_management/auth/hooks'
File: frontend/src/router/AppRoutes.jsx
Import and integrate authentication routes into createAppRouter:
import Root from "../layouts/Root";
import Home from "../pages/Home";
import { createAuthRoutes } from './AuthRouter';
export function createAppRouter(config) {
const authRoutes = createAuthRoutes(config);
return [
{
path: "/",
element: <Root />,
children: [
{
path: "/",
element: <Home />,
},
...authRoutes
],
},
];
}
File: frontend/src/router/AuthRouter.jsx
Rename the exported function and export the routes array:
Change:
function createRouter (config) {
return createBrowserRouter([
{
path: '/',
element: <AuthChangeRedirector><Root /></AuthChangeRedirector>,
children: [
// ... routes
]
}
])
}
export default function Router () {
const [router, setRouter] = useState(null)
const config = useConfig()
useEffect(() => {
setRouter(createRouter(config))
}, [config])
return router ? <RouterProvider router={router} /> : null
}
To:
export function createAuthRoutes (config) {
return [
// ... all the route objects from the children array
]
}
Remove the /calculator route as it's not needed.
File: frontend/src/user_management/lib/allauth.jsx
Find the redirectToProvider function and update the callback_url parameter.
Change:
callback_url: window.location.protocol + '//' + window.location.host + callbackURL,
To:
callback_url: callbackURL,
This configuration ensures social authentication callbacks use the correct backend URL instead of the frontend host.
File: frontend/vite.config.js
Add the /_allauth proxy configuration to forward authentication requests to the Django backend.
Add to the proxy object:
'/_allauth': {
target: 'https://localhost:8000',
changeOrigin: true,
secure: false, // Allow self-signed certificates
},
Expected result:
proxy: {
'/api': {
target: 'https://localhost:8000',
changeOrigin: true,
secure: false,
},
'/_allauth': {
target: 'https://localhost:8000',
changeOrigin: true,
secure: false,
},
}
First, search the project to determine if a navbar or header component exists.
Import the auth status helper and toggle the navigation link based on whether the user is logged in:
import { useAuthStatus } from "@/user_management/auth";
import { Link } from "react-router-dom";
const [, authInfo] = useAuthStatus();
{authInfo.isAuthenticated ? (
<Link to="/account/logout">
<NavigationMenuLink className={navigationMenuTriggerStyle()}>
Logout
</NavigationMenuLink>
</Link>
) : (
<Link to="/account/login">
<NavigationMenuLink className={navigationMenuTriggerStyle()}>
Login
</NavigationMenuLink>
</Link>
)}
Add auth-aware navigation links to the landing page.
File: frontend/src/pages/Home.jsx
Import the required dependencies at the top:
import { useAuthStatus } from "@/user_management/auth";
import { Link } from "react-router-dom";
Add the navigation links in the component JSX:
const [, authInfo] = useAuthStatus();
return (
<div>
<nav style={{ padding: '1rem', borderBottom: '1px solid #ccc' }}>
{authInfo.isAuthenticated ? (
<Link to="/account/logout" style={{ marginRight: '1rem' }}>
Logout
</Link>
) : (
<Link to="/account/login" style={{ marginRight: '1rem' }}>
Login
</Link>
)}
</nav>
{/* Rest of Home page content */}
</div>
);
Note: Linking to /account/logout ensures authenticated users reach the confirmation screen before finalizing the logout. Anonymous visitors continue to see the Login link.
This step configures multi-step signup flows (like email verification + passkey creation) to navigate correctly between steps without intermediate redirects.
Files:
frontend/src/user_management/account/Signup.jsxfrontend/src/user_management/mfa/SignupByPasskey.jsxAdd the following imports at the top of each signup component:
import { useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { pathForFlow } from '../auth'
Inside each component, instantiate the navigate function:
const navigate = useNavigate()
Add a useEffect hook that watches for pending flows in the response:
useEffect(() => {
if (response.content) {
const pending = response.content?.data?.flows?.find(flow => flow.is_pending)
if (pending) {
navigate(pathForFlow(pending), { replace: true })
}
}
}, [response.content, navigate])
This configuration ensures users are redirected to the next step in the signup flow (e.g., email verification) without leaving the signup page in the history stack.
File: frontend/src/user_management/auth/routing.jsx
Update the AuthChangeRedirector component to check for pending flows before redirecting to the default login redirect URL.
In the LOGGED_IN branch, add logic to call pathForPendingFlow(auth) before defaulting to LOGIN_REDIRECT_URL:
if (auth.status === AuthStatus.LOGGED_IN) {
const pendingPath = pathForPendingFlow(auth)
if (pendingPath) {
navigate(pendingPath, { replace: true })
} else {
navigate(LOGIN_REDIRECT_URL, { replace: true })
}
}
This logic prevents users from being redirected to the dashboard when pending authentication steps remain.
File: frontend/src/user_management/account/VerifyEmailByCode.jsx
Replace the static <Navigate> component return with a useEffect hook that handles flow-based redirects.
Add the required imports:
import { useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { pathForFlow } from '../auth'
Instantiate navigate:
const navigate = useNavigate()
Replace the <Navigate> return with a useEffect that redirects based on the response:
useEffect(() => {
const content = response.content
if (!content) {
return
}
const flows = content.data?.flows
if (flows?.length) {
const pending = flows.find(flow => flow.is_pending)
if (pending) {
navigate(pathForFlow(pending), { replace: true })
return
}
}
if (content.status === 200) {
navigate('/account/email', { replace: true })
} else if (content.status === 401) {
navigate('/account/login', { replace: true })
}
}, [response.content, navigate])
This configuration ensures email verification redirects to the next pending flow step (e.g., passkey creation) or falls back to the appropriate default page.
Run the comprehensive authentication flow test suite to validate the entire integration. This step confirms all authentication flows work correctly end-to-end.
Activate the Django virtual environment and install Playwright for browser automation testing:
source venv/bin/activate
# Install pytest only if missing
python -c "import pytest" 2>/dev/null || pip install 'pytest>=7.4,<9.0'
# Install playwright only if missing
python -c "import playwright" 2>/dev/null || pip install playwright
# Install chromium only if Playwright hasn't installed it yet
playwright show-browsers | grep -q "chromium" \
|| playwright install chromium
Before running tests, verify both servers are running and start them if needed.
Check if backend is running on port 8000:
lsof -i :8000
If backend is not running, start it:
Activate the virtual environment, and run the startup script in the background:
source venv/bin/activate && \
uvicorn backend.asgi:application \
--host 127.0.0.1 \
--port 8000 \
--ssl-keyfile ./certs/localhost+2-key.pem \
--ssl-certfile ./certs/localhost+2.pem
Check if frontend is running on port 5173:
lsof -i :5173
If frontend is not running, start it:
Start the development server in the background:
npm --prefix ./frontend run dev
Wait for servers to be ready:
Allow a few seconds for both servers to fully initialize before proceeding with tests.
Execute the test suite:
From the Django project root with the virtual environment activated:
Activate the virtual environment source venv/bin/activate and run the test script at: scripts/test_auth_flows.py
The test suite includes:
Prerequisites for testing:
https://localhost:8000https://localhost:5173sent_emails/ directoryTest execution:
headless=False) for debuggingverbosity=2) shows detailed test progressNote: Tests run sequentially and may take several minutes to complete due to browser automation and wait times for email delivery.
Read the styling reference guide from the skill's bundled resources and write it to the project root for later use.
The styling guide is located at references/styling-guide.md within this skill's directory. Read this file and write its contents to react-allauth-styling-reference.md in the project root.
This file lists all 35 authentication components that require styling and can be referenced by styling skills. Delete this file after styling is complete.
Terminate any background commands or servers started during the configuration process.
This skill should be used when the user asks to "create an agent", "add an agent", "write a subagent", "agent frontmatter", "when to use description", "agent examples", "agent tools", "agent colors", "autonomous agent", or needs guidance on agent structure, system prompts, triggering conditions, or agent development best practices for Claude Code plugins.
This skill should be used when the user asks to "create a slash command", "add a command", "write a custom command", "define command arguments", "use command frontmatter", "organize commands", "create command with file references", "interactive command", "use AskUserQuestion in command", or needs guidance on slash command structure, YAML frontmatter fields, dynamic arguments, bash execution in commands, user interaction patterns, or command development best practices for Claude Code.
This skill should be used when the user asks to "create a hook", "add a PreToolUse/PostToolUse/Stop hook", "validate tool use", "implement prompt-based hooks", "use ${CLAUDE_PLUGIN_ROOT}", "set up event-driven automation", "block dangerous commands", or mentions hook events (PreToolUse, PostToolUse, Stop, SubagentStop, SessionStart, SessionEnd, UserPromptSubmit, PreCompact, Notification). Provides comprehensive guidance for creating and implementing Claude Code plugin hooks with focus on advanced prompt-based hooks API.