Skip to Content
FrontendData Layer

Data Layer

The data layer is generated from Django ViewSets via a validated OpenAPI contract. The pinned Orval target emits operations, React Query v5 hooks/query keys, Zod schemas, and MSW handlers. The application-owned runtime boundary handles authentication, refresh, transport, and normalized errors.

For Django ViewSet patterns see App Design Guide — ViewSets. For SSR data fetching see SSR & Hydration.

Generation Pipeline

Django ViewSets → drf-spectacular → OpenAPI schema → python manage.py gen → app/_lib/api/generated/<domain>/

A generated target (the path of a Target in generation.py) contains:

generated/ ├── endpoints/ # Orval tags-split operations and hooks ├── models/ # TypeScript and Zod schemas ├── mocks/ # MSW handlers └── index.ts # Stable project barrel

Never edit generated/ manually. Regenerate with python manage.py gen.

Runtime boundary

Generated operations use the shared runtime/mutator boundary from @djangocfg/api. Application code does not create a second API client or token store:

import { auth, djangoFetch } from '@djangocfg/api'; export { auth, djangoFetch };

The generated runtime/orval-mutator.ts re-exports this boundary. It adds auth headers, refresh/retry behavior, normalized errors, and Zod response parsing. For SSR, use the imperative operation or its generated query options; do not instantiate a browser client in a Server Component.

import { cryptoCoinsList } from '@api/generated/endpoints'; const coins = await cryptoCoinsList({ page: 1 });

Zod Validation

Generated operations check every response against its Zod schema at runtime. The check reports; it does not block:

// Orval operation; the generated code passes the schema to djangoFetch. const response = await cryptoCoinsList({ page: 1 }); // On a match, `response` is the parsed data. On a miss, it is the body exactly // as the server sent it, and `zod-validation-error` was dispatched on `window`.

To reject a miss instead, pass validation: 'strict'; the call then rejects with the ZodError. Listen for misses with onValidationError from @djangocfg/api. See Runtime for the full option list.

React Query Hooks and Query Keys

Generated hooks wrap operations with TanStack Query:

import { useQueryClient } from '@tanstack/react-query'; import { useCryptoCoinsList, getCryptoCoinsListQueryKey, } from '@api/generated/endpoints'; const queryClient = useQueryClient(); const query = useCryptoCoinsList({ page: 1 }, { query: { staleTime: 60_000 }, }); queryClient.invalidateQueries({ queryKey: getCryptoCoinsListQueryKey({ page: 1 }), });

Use the generated enabled option to conditionally skip fetching. After a mutation, invalidate the generated query key with queryClient; never hand-build or globally mutate string-based cache keys.

Type Re-Export Pattern (types.ts)

Components import types from the context’s types.ts, never from generated/ directly:

// contexts/<domain>/types.ts — SINGLE SOURCE OF TRUTH import { CoinListing } from '@api/generated/models'; // Re-export from the generated model barrel, not a disposable file path. export { CoinListing } from '@api/generated/models'; export type { CoinListingOutput } from '@api/generated/models'; // App-specific types stay handwritten. export type CatalogItem = CoinListing; // App-specific types export interface FilterState { brand: string | null; source: string | null; minPrice: number | null; maxPrice: number | null; page: number; pageSize: number; }

The dual export pattern (export const + export type for the same name) allows both runtime usage and type-level usage from a single import.

Query configuration

Configure TanStack Query once at the application boundary and keep endpoint freshness close to the generated hook:

OptionUse CaseGuidance
staleTimeReference/static dataAvoid unnecessary refetches
gcTimeInactive dataBound retained cache lifetime
enabledConditional queriesWait for required input

The provider owns retry and focus policies; generated query keys own cache identity.

CFG API vs Custom API

Two tiers of API clients:

TierPackageScope
CFG API@djangocfg/apiUniversal: accounts, auth, JWT, 2FA
Custom APIgenerated/ per appApp-specific: catalog, projects, terminals

Extensions use createExtensionAPI() from @djangocfg/ext-base to share auth storage with the core API client. See Extensions recipe.

Auth token & logging

The @djangocfg/api runtime boundary handles tokens, headers, refresh, and normalized errors for generated operations. One behavior worth knowing:

  • Role-aware console logging. All @djangocfg/* loggers share a runtime level (applyRoleLogPolicy / setLogLevel from @djangocfg/api). AuthProvider applies it automatically: admins (and dev) get debug logs, regular users in production get a clean console (errors only). Errors still reach @djangocfg/devtools regardless.

Rules

  1. Never edit generated/ directories — regenerate with python manage.py gen.
  2. Import from generated/endpoints, generated/models, or an app-owned API barrel; do not couple application code to disposable operation files.
  3. Use generated query-key factories for cache reads and invalidation.
  4. Keep authentication, refresh, error normalization, and transport in the runtime boundary.
  5. Use enabled for conditional queries; never call hooks conditionally.
Last updated on