Skip to Content
FeaturesBundled ExtensionsUser ManagementAccountsFrontend Integration

Frontend Integration

Two packages cover the full frontend auth stack:

PackageWhat it provides
@djangocfg/apiType-safe API client, hooks, JWT management, server middleware
@djangocfg/layoutsAuthLayout — drop-in multi-step auth UI

AuthLayout

The fastest path — a complete authentication UI from @djangocfg/layouts. One component, all steps handled.

// app/auth/page.tsx import { AuthLayout } from '@djangocfg/layouts' export default function LoginPage() { return ( <AuthLayout redirectUrl="/dashboard" termsUrl="/terms" privacyUrl="/privacy" /> ) }

Auth steps

identifier → otp → success → redirect

The code screen opens as soon as the email is submitted and rolls back to the identifier step if the request fails. The resend link counts down from the server’s resend_in (30 s fallback). Sign-ins are remembered for 30 days by default.

If the account has 2FA, a challenge dialog opens over the page after the code is accepted — it is not a step of the form.

Props

PropTypeDefaultDescription
redirectUrlstring/privateWhere to go after success, unless a saved return URL exists
sourceUrlstring—App URL for analytics / OTP emails
oauthProviders('github' | 'google')[]server listOptional. Only narrows (and orders) the providers the server reports; it cannot show one the server has not enabled
enableGithubAuthboolean—Deprecated, no effect. Buttons come from GET /cfg/accounts/oauth/providers/
logoReactNode—Brand mark (inline SVG, <img>, lock-up); sits on the media half or above the form
variant'fullsplit' | 'centered' | 'split''fullsplit'Shell layout
termsUrlstring—Terms of service link
privacyUrlstring—Privacy policy link
supportUrlstring—Support page link
marketingConsentAuthMarketingConsentConfig—Opt-in marketing checkbox on the identifier step (absent ⇒ no checkbox)
childrenReactNode—Custom header — rendered on identifier step only

Callbacks

<AuthLayout onIdentifierSuccess={(identifier) => console.log('OTP sent to', identifier)} onOTPSuccess={() => console.log('verified')} onOAuthSuccess={(user, isNewUser, provider) => console.log(provider, user)} onError={(message) => console.error(message)} />

Accessing step state from child components

import { useAuthFormContext } from '@djangocfg/layouts' const { step, identifier, isLoading } = useAuthFormContext()

Two-factor challenge

The form holds no 2FA state. A step that receives requires_2fa publishes the pending session, and TwoFactorChallengeDialog — mounted by AuthLayout — opens over the page: authenticator code, backup-code fallback, attempts left.

import { beginTwoFactorChallenge, useTwoFactorChallenge } from '@djangocfg/api/auth' import { TwoFactorChallengeDialog, TwoFactorSetup } from '@djangocfg/layouts' beginTwoFactorChallenge({ sessionId }) // what a sign-in step does on requires_2fa const challenge = useTwoFactorChallenge() // { sessionId } | null

TwoFactorChallengeDialog takes onVerified, onCancel and redirectUrl; without onVerified it navigates after success. TwoFactorSetup (QR, confirmation code, backup codes) is the enrol flow for a settings page and shows the backup codes before calling onComplete.

Pass marketingConsent to render an opt-in checkbox inside the identifier form. The checkbox value is sent with the OTP request as marketing_consent + consent_disclosure_version and surfaces backend-side through the user_email_verified signal once the email is verified — see OTP & Brute-Force Protection.

import { AuthLayout } from '@djangocfg/layouts' import { useCfgAccountsOtpConsentPolicyRetrieve } from '@djangocfg/api/hooks' export default function LoginPage() { // Server-decided default from GET /cfg/accounts/otp/consent-policy/ // (CF-IPCountry → "checked" | "unchecked") const { data: policy } = useCfgAccountsOtpConsentPolicyRetrieve() return ( <AuthLayout sourceUrl="https://myapp.com" marketingConsent={{ enabled: true, disclosureVersion: 'product-updates-reg-v1', label: 'Send me product updates', // your own i18n — the package ships no copy defaultChecked: policy ? policy.marketing_consent_default === 'checked' : undefined, }} /> ) }

Default resolution: an explicit defaultChecked (typically the server policy) always wins; while it is undefined (policy loading/unavailable) a browser-timezone heuristic is the fallback (Europe/* ⇒ unchecked). A user’s own toggle is never overridden by either.


AuthProvider

AuthProvider from @djangocfg/api/auth manages tokens, user state, and auto-refresh. Required for all auth hooks.

When using @djangocfg/layouts, AuthProvider is already included inside AppLayout / BaseApp — no manual setup needed.

For standalone usage:

// app/layout.tsx import { AuthProvider } from '@djangocfg/api/auth' export default function RootLayout({ children }) { return ( <html lang="en"> <body> <AuthProvider config={{ routes: { auth: '/auth', defaultCallback: '/dashboard' } }}> {children} </AuthProvider> </body> </html> ) }

Auth Hooks

useAuth — user state and OTP methods

'use client' import { useAuth } from '@djangocfg/api/auth' const { user, isAuthenticated, isLoading, requestOTP, verifyOTP, logout } = useAuth()
ValueTypeDescription
userUserProfile | nullCurrent user
isAuthenticatedboolean—
isLoadingbooleanInitial auth check in progress
isAdminUserbooleanuser.is_staff || user.is_superuser
status'resolving' | 'authenticated' | 'anonymous'The one linear state; resolving until the client has read the session and its profile
isHydratedbooleanfalse on the server and during the hydration render, true from the first commit after mount
requestOTPfnSend OTP to email — requestOTP(identifier, sourceUrl?, consent?); consent = { marketingConsent, disclosureVersion }; resolves with resendIn seconds when the server states one
verifyOTPfnVerify code → stores JWT
logoutfnClears tokens

Server rendering. The server never sees the browser’s stored session, so it renders a guest. To match that HTML, useAuth() also renders a guest on the client’s first render: user is null and isAdminUser is false until isHydrated turns true, even for a signed-in visitor whose profile is cached. The cached profile is applied right after mount, before paint, so there is no visible guest frame. Read user / isAdminUser directly in server-rendered components; no app-side mount gate is needed. Gate on isHydrated (or status !== 'resolving') only when “guest” and “not known yet” must look different, e.g. to avoid flashing a “Sign in” button. Before @djangocfg/api 2.1.656 the profile was read from the cache during the first render, which caused React hydration error #418 wherever the profile changed the markup.

useAuthGuard — route protection

'use client' import { useAuthGuard } from '@djangocfg/api/auth' const { isAllowed } = useAuthGuard({ redirectTo: '/auth', requireAuth: true }) if (!isAllowed) return null

useAuthForm — multi-step form state

'use client' import { useAuthForm } from '@djangocfg/api/auth' const { step, // 'identifier' | 'otp' | 'success' identifier, setIdentifier, otp, setOtp, isLoading, error, isRateLimited, rateLimitLabel, // countdown string e.g. "1:30" resendSeconds, resendLabel, // countdown before another code may be requested handleIdentifierSubmit, handleOTPSubmit, handleResendOTP, handleBackToIdentifier, } = useAuthForm({ sourceUrl: window.location.origin, redirectUrl: '/dashboard', requireTermsAcceptance: false, onIdentifierSuccess: (id) => {}, onOTPSuccess: () => {}, onError: (msg) => {}, })

useOAuthLogin — OAuth

One hook for every provider (github, google). AuthLayout already uses it; call it directly only for a custom screen.

'use client' import { useOAuthLogin, useOAuthProviders } from '@djangocfg/api/auth' const { providers, isReady } = useOAuthProviders() // enabled providers, server order const { start, complete, isLoading, loadingProvider, error, errorCode } = useOAuthLogin({ sourceUrl: window.location.origin, redirectUrl: '/dashboard', onSuccess: (user, isNewUser, provider) => {}, onError: (message, code) => {}, }) // start('google') → same-tab redirect to the provider // complete(provider, code, state) → on the /auth?provider=<id> page

useOAuthProviders keeps the last answer in sessionStorage (cfg.auth.oauth_providers), so the buttons are there on a reload or after a failed attempt while the server answer revalidates; a failed request shows that list, else none. Error code values are the generated OAuthErrorCodeEnum.

complete requires the state saved by start, single use. A missing or different state fails with invalid_state. The saved return URL is honoured, then redirectUrl, then /private. AuthLayout handles the /auth?provider=<id> callback itself, strips code/state from the URL and shows a translated message for each error code (origin_not_allowed also gets a hint for developers).

useGithubAuth is a deprecated alias of useOAuthLogin('github'), kept for one minor.

Provider icons

Everything lives in packages/layouts/src/layouts/AuthLayout/components/oauth/; only OAuthCallback is a package export. A provider is one line in providers/registry.ts (OAUTH_PROVIDERS: brand name and icon); the buttons, the Continue with {provider} label, the notices and the error copy all read that table. GoogleIcon is the four-colour “G” and keeps its own colours in light and dark; GithubIcon uses currentColor. Both are aria-hidden; the button text carries the name. A provider the backend adds is a type error in the registry until it has a name and an icon.

Testing sign-in in Storybook

AuthFlow.stories.tsx runs the real hooks against a faked network. oauthApiMock from @djangocfg/layouts/testing (used as a story beforeEach) answers GET /oauth/providers/ and the authorize and callback POSTs at the fetch level, for any of the 16 error codes with their HTTP status. It refuses every other request and holds back full-page navigations, so the story iframe stays put; getOAuthApiMock() returns the recorded calls and navigations for play assertions.

  • Pair it with MockAuthFormProvider and its oauthFromServer prop for the button list, or render the whole AuthLayout for a callback round trip.
  • seedOAuthBrowser puts the provider’s parameters in the address bar and the stored state in sessionStorage, as a real return leaves them.
  • OAUTH_SERVER_ERROR_CODES and mockOAuthState are exported from the same entry point.
pnpm --filter @djangocfg/storybook test:stories:contracts # sign-in contract stories pnpm --filter @djangocfg/storybook test:stories:all

The runner drives Playwright Chromium. Install it once with pnpm --filter @djangocfg/storybook exec playwright install chromium.

useTwoFactor — verify, set up, manage

'use client' import { useTwoFactor } from '@djangocfg/api/auth' const two = useTwoFactor({ verify: { redirectUrl: '/dashboard' } }) await two.verify.verifyTOTP(sessionId, '123456') // login challenge await two.verify.verifyBackupCode(sessionId, code)

The sub-hooks (useTwoFactorVerify, useTwoFactorSetup, useTwoFactorStatus) can be used alone.

useTwoFactorSetup — enable/disable 2FA for authenticated users

'use client' import { useTwoFactorSetup } from '@djangocfg/api/auth' const { setupData, backupCodes, setupStep, startSetup, confirmSetup } = useTwoFactorSetup()

useTwoFactorStatus — check and manage 2FA status

'use client' import { useTwoFactorStatus } from '@djangocfg/api/auth' const { has2FAEnabled, devices, fetchStatus, disable2FA } = useTwoFactorStatus()

Server Components & React Query Hooks

Server component (fetcher)

import { cfgAccountsProfileRetrieve } from '@djangocfg/api' export default async function ProfilePage() { const profile = await cfgAccountsProfileRetrieve() return <div>{profile.email}</div> }

Client hook (React Query)

'use client' import { useCfgAccountsProfileRetrieve } from '@djangocfg/api' const { data: profile, isPending, refetch } = useCfgAccountsProfileRetrieve()

Server Middleware

Proxies /media/* and /api/* to the Django backend, forwarding cookies and auth headers automatically:

// middleware.ts import { proxyMiddleware } from '@djangocfg/api/auth/server' import { NextRequest } from 'next/server' export function middleware(request: NextRequest) { return proxyMiddleware(request) } export const config = { matcher: ['/media/:path*', '/api/:path*'], }

Analytics Events

Auth events are tracked automatically when analytics is configured in AppLayout:

EventTrigger
AUTH_LOGIN_SUCCESSOTP verify or OAuth success
AUTH_LOGOUTlogout() called
AUTH_OAUTH_START / _SUCCESS / _FAILProvider sign-in flow (Google or GitHub)
AUTH_2FA_SETUP_COMPLETE2FA enabled
AUTH_2FA_VERIFY_SUCCESS / _FAIL2FA code verification

Environment Variables

NEXT_PUBLIC_API_URL=http://localhost:8000

See Also

TAGS: accounts, frontend, AuthLayout, useAuth, useAuthForm, marketing-consent, @djangocfg/api, @djangocfg/layouts DEPENDS_ON: [accounts/index]

Last updated on