@djangocfg/api
The generated REST client for a django-cfg backend, the small runtime under it, and the React auth layer.
The REST surface is generated by django-cfg's Python generator with pinned Orval 8.48: operation functions,
TanStack Query v5 hooks and query keys, Zod schemas and MSW handlers. The runtime (src/runtime/) is hand-written:
the API origin, one session store per page, refresh, errors and validation events.
Install
pnpm add @djangocfg/api @tanstack/react-query zod
@tanstack/react-query, zod, react, next and consola are peers. Apps on @djangocfg/layouts get their
QueryClient from BaseApp; they do not mount a provider of their own.
Entry points
| Import |
Contents |
@djangocfg/api |
Generated operations, hooks, query keys and Zod models; the runtime (djangoFetch, configureApi, auth, errors, drfPageParams) |
@djangocfg/api/auth |
AuthProvider, useAuth, sign-in, 2FA and guard hooks |
@djangocfg/api/auth/server |
Next.js middleware (proxyMiddleware) |
@djangocfg/api/storage |
cfg.<area>.<name> storage keys, createStorage, single sign-in helpers. No React, no client |
@djangocfg/api/clients |
Generated operations and models, plus the auth store |
@djangocfg/api/hooks |
Domain hooks (useApiKey) and selected generated hooks |
@djangocfg/api/mocks |
Generated MSW handlers and Faker factories |
There is no @djangocfg/api/query any more. ApiQueryProvider and createApiQueryClient are gone: BaseApp owns
the QueryClient.
Generated REST operations
Each OpenAPI tag is one module under src/_api/generated/endpoints/; the package root re-exports all of them. Use
the operation function in imperative code and the hook for client state. Invalidate with the generated query key:
import { useQueryClient } from '@tanstack/react-query';
import {
cfgAccountsProfileRetrieve,
getCfgAccountsProfileRetrieveQueryKey,
useCfgAccountsProfilePartialUpdate,
useCfgAccountsProfileRetrieve,
} from '@djangocfg/api';
// Imperative: event handlers, route handlers, server code.
export const loadProfile = (signal?: AbortSignal) => cfgAccountsProfileRetrieve({ signal });
// Client state: the hooks use the QueryClient BaseApp provides.
export function ProfileName() {
const queryClient = useQueryClient();
const profile = useCfgAccountsProfileRetrieve();
const rename = useCfgAccountsProfilePartialUpdate({
mutation: {
onSuccess: () => queryClient.invalidateQueries({ queryKey: getCfgAccountsProfileRetrieveQueryKey() }),
},
});
if (profile.isPending) return null;
return (
<button type="button" onClick={() => rename.mutate({ data: { first_name: 'Ada' } })}>
{profile.data?.email}
</button>
);
}
Names come from the backend operationId. Do not alias them in app code. Every operation takes
options?: DjangoRequestInit and every hook takes request with the same type; TError is ApiClientError.
Full surface (Zod, MSW, infinite queries, realtime metadata, request flags): @docs/GENERATED_CLIENT.md.
API origin
One resolver (resolveApiOrigin, src/runtime/api-origin.ts) serves every operation, the token refresh and the
profile guard. It reads only the literal process.env.NEXT_PUBLIC_* names, the form Next inlines.
| Where |
Order |
| Browser |
configureApi({ apiUrl }) / setApiOrigin, then NEXT_PUBLIC_STATIC_BUILD=true (same origin), then NEXT_PUBLIC_API_PROXY_URL when defined ('' = same origin), then NEXT_PUBLIC_API_URL, then allowRelative |
| Server |
an explicit absolute origin, then NEXT_PUBLIC_API_URL. The proxy and static modes are ignored |
origin: 'direct' |
as on the server, in the browser too |
Nothing resolved: the request fails with APIConfigurationError before fetch. AuthProvider calls
configureApi with auth.apiUrl. The full table: docs → API generation → Runtime.
Errors
import { APIError, NetworkError, useCfgAccountsProfileRetrieve } from '@djangocfg/api';
export function ProfileError() {
const { error } = useCfgAccountsProfileRetrieve();
if (error instanceof APIError) return <p>{error.errorMessage}</p>;
if (error instanceof NetworkError) return <p>Offline</p>;
return null;
}
errorMessage reads DRF detail (a string or an array), error, message, non_field_errors, then the first
field error. fieldErrors maps each field to its messages. isPermissionError is 403 only; isAuthError is 401.
Details: @docs/ERROR_HANDLING.md.
Auth Module
import { AuthProvider, useAuth } from '@djangocfg/api/auth';
// Provider
<AuthProvider config={{ routes: { auth: '/auth', defaultCallback: '/private' } }}>
{children}
</AuthProvider>
// Hook
const { user, isAuthenticated, requestOTP, verifyOTP, logout } = useAuth();
With @djangocfg/layouts, BaseApp mounts AuthProvider for you.
Auth Hooks
import {
useAuth, // Main auth context
useAuthGuard, // Route protection
useAuthForm, // OTP form state machine
useOAuthLogin, // GitHub / Google OAuth
useOAuthProviders, // providers enabled on the server
useTwoFactor, // 2FA verification
useTwoFactorSetup, // 2FA setup flow
useTwoFactorStatus, // 2FA status / disable
useDeleteAccount, // Account deletion
} from '@djangocfg/api/auth';
Guard resolvers
The "spinner vs redirect vs render" decision is pure and separately testable.
useAuthGuard (and @djangocfg/layouts' PrivateLayout) just wire React state
into these:
import {
resolveGuardIsLoading, // show the preloader?
shouldRedirectToAuth, // no session → send to the auth form
isForbidden, // signed in, but lacks the required privilege
resolveGuardIsAuthenticated,
type GuardInput,
} from '@djangocfg/api/auth';
GuardInput takes two optional fields for the role gate: requireStaff (the
route needs staff/admin) and isAdminUser (from useAuth() — the
is_staff || is_superuser fold, never one flag).
isForbidden is deliberately not a redirect condition: the session is
valid, so the auth form cannot fix it, and redirecting would loop on the saved
URL. Render a distinct "not authorised" state instead. resolveGuardIsLoading
returns false once forbidden, so the preloader never spins on it.
Single sign-in host
<AuthProvider config={{ sso: true }}> (or BaseApp auth={{ sso: true }}) makes auth.<apex> the only sign-in page for
every subdomain: followers redirect there with ?next=<url> and are sent back; sign-out clears the session on all of
them. The session is the shared cookie pair on .<apex>. Off unless set, and off on localhost (one console line).
Pure helpers for middleware and clients are in @djangocfg/api/storage: safeNext (the only gate for next),
deriveAuthHost, resolveSso, buildSsoLoginUrl. useAuth().sso reports the state. Details:
@docs/AUTHENTICATION.md.
Storage keys
Every browser-storage key is cfg.<area>.<name> (framework) or
<owner>.<area>.<name> (app). Use the registry, never a literal or raw localStorage:
import { CFG_KEYS, cfgStorage, createStorage } from '@djangocfg/api/storage';
cfgStorage.read(CFG_KEYS.email.key);
cfgStorage.clearAll(); // sign-out: removes personal keys
const storage = createStorage('kino');
storage.writeJSON(storage.key('player', 'volume'), 0.4);
Old key names are not migrated. Full rules, the key list and cross-tab behavior:
@docs/STORAGE_KEYS.md.
The session store
The tokens live in one auth store per page. Its state sits on
globalThis[Symbol.for('djangocfg.api.auth')], so the root, /auth, /clients and /hooks entries, ESM and CJS
copies, share one session. The tokens are kept in cookies only (cfg.auth.access_token, cfg.auth.refresh_token;
not HttpOnly, see @docs/SECURITY.md).
import { auth } from '@djangocfg/api';
auth.getToken(); // the current access token, re-read from the cookie
auth.isAuthenticated(); // a live access token, or a live refresh token (`exp`-aware)
auth.onSessionExpired(() => console.info('signed out'));
- Other tabs see a sign-in or sign-out through a localStorage signal (
cfg.auth.session_signal, no token), focus,
visibility and cookieStore.
- A refresh runs once per page and, with Web Locks, once per origin (
djangocfg.api.refresh). The tokens are
re-read inside the lock, so a rotating refresh token is never sent twice.
- Only a 400/401/403 from the refresh endpoint, or a body without
access, ends the session. A network error, a
missing origin or a 5xx keeps it, and the request fails with that cause.
setStorageMode keeps cookies and warns for another mode. setBaseUrl is setApiOrigin.
Logging — role-aware verbosity
All @djangocfg/* consola loggers read one global runtime level so the console
is clean for end users and verbose for admins/devs — like big SaaS apps.
import { applyRoleLogPolicy, setLogLevel } from '@djangocfg/api';
// Usually automatic: AuthProvider calls this on login/logout.
// admin (is_staff/is_superuser) or dev → debug; prod regular user → errors only.
applyRoleLogPolicy({ isAdmin: Boolean(user?.is_staff || user?.is_superuser) });
// Manual override (0 silent · 1 error · 2 warn · 3 info · 4 debug · 5 trace):
setLogLevel(0);
Errors still flow to @djangocfg/devtools regardless of console level, so prod
incidents stay diagnosable.
Env flags
@djangocfg/api is the lowest shared package, so env flags live here (single
source of truth):
import { isDev, isProd, isBrowser, isStaticBuild } from '@djangocfg/api';
Server Middleware
// middleware.ts
import { proxyMiddleware } from '@djangocfg/api/auth/server';
export function middleware(request: NextRequest) {
return proxyMiddleware(request);
}
export const config = {
matcher: ['/media/:path*', '/api/:path*'],
};
Environment
| Variable |
Effect |
NEXT_PUBLIC_API_URL |
The API host. Browser and server |
NEXT_PUBLIC_API_PROXY_URL |
Browser only. Set: requests go there; set to '': same-origin relative |
NEXT_PUBLIC_STATIC_BUILD |
true: browser requests are same-origin relative (static export) |
NEXT_PUBLIC_API_KEY |
Default X-API-Key, after auth.setApiKey and the persisted key |
Read them only as literal process.env.NEXT_PUBLIC_* in your own code too. Next does not inline
globalThis.process.env, an alias or a destructure, and the value is then empty in the browser.
Regenerate the client
# here: regenerate this package's tree (manage.py gen --target packages), then build
make generate
# or every target of the reference project
cd ../../../django && make gen
The generator type-checks the tree before it replaces the old one. Do not run Orval by hand. Generator internals:
django_cfg/modules/django_generator/openapi/README.md.