@djangocfg/api

中文文档
2.1.655发布于 2026/11/12MITTypeScriptESM + CJS零依赖近 30 天下载 1.9万

Auto-generated TypeScript API client with React hooks, SWR integration, and Zod validation for Django REST Framework backends

原始使用文档
文档目录15 节
  1. Install
  2. Entry Points
  3. Generated API Classes
  4. Auth Module
  5. Auth Hooks
  6. Guard resolvers
  7. Single sign-in host
  8. Storage keys
  9. Token storage
  10. Logging — role-aware verbosity
  11. Env flags
  12. Type Namespaces
  13. Server Middleware
  14. Environment
  15. Regenerate Client

@djangocfg/api

Type-safe API client and auth system for DjangoCFG applications.

Install

pnpm add @djangocfg/api

Entry Points

EntryImportDescription
Main@djangocfg/apiAPI classes, types, fetchers, schemas
Auth@djangocfg/api/authAuth providers, hooks, utilities
Auth Server@djangocfg/api/auth/serverNext.js proxy middleware
Storage@djangocfg/api/storageCookie/storage keys; single sign-in helpers (safeNext, deriveAuthHost, buildSsoLoginUrl)
Clients@djangocfg/api/clientsPre-configured API instances

Generated API Classes

One class per OpenAPI tag. Import directly and call static methods:

import {
  CfgAccounts,          // OTP login
  CfgAccountsProfile,   // Profile CRUD
  CfgAccountsOauth,     // GitHub OAuth
  CfgAccountsAuth,      // Token refresh
  CfgAccountsApiKey,    // API key management
  CfgTotp,              // TOTP devices / disable
  CfgTotpSetup,         // TOTP setup / confirm
  CfgTotpVerify,        // TOTP verify / backup
  CfgTotpBackupCodes,   // Backup codes
} from '@djangocfg/api';

// OTP login
const result = await CfgAccounts.cfgAccountsOtpVerifyCreate({
  body: { identifier, otp },
});

// Profile
const profile = await CfgAccountsProfile.cfgAccountsProfileRetrieve();

// Token refresh
const tokens = await CfgAccountsAuth.cfgAccountsTokenRefreshCreate({
  body: { refresh },
});

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();

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.

Token storage

The token lives in the shared auth store (localStorage by default, switchable to cookie):

import { auth } from '@djangocfg/api';

auth.getToken();              // current access token
auth.setStorageMode('cookie'); // SSR-readable cookie instead of localStorage

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: 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';

Type Namespaces

import type { AccountsTypes, TotpTypes } from '@djangocfg/api';

type User = AccountsTypes.User;
type Device = TotpTypes.TotpDevice;

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

NEXT_PUBLIC_API_URL=http://localhost:8000

Regenerate Client

# From django solution directory
make api

版本与发布记录

@djangocfg/api 共发布 672 个版本,首次发布于 2025/10/13;过去 12 个月发布了 630 个版本。

版本发布日期距今
2.1.655latest2026/11/12今天
2.1.6532026/11/12今天
2.1.6522026/11/11今天
2.1.6512026/11/111 天前
2.1.6502026/11/111 天前
2.1.6482026/11/111 天前

关于 @djangocfg/api 的常见问题

@djangocfg/api 是什么?

Auto-generated TypeScript API client with React hooks, SWR integration, and Zod validation for Django REST Framework backends

如何安装 @djangocfg/api?

在项目目录运行 npm install @djangocfg/api,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:swr(^2.3.7)、zod(^4.3.6)、next(^16.4.5)、react(^19.0.0)、consola(^3.4.2)、p-retry(^7.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@djangocfg/api 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@djangocfg/api 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@djangocfg/api 可以商用吗?

@djangocfg/api 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@djangocfg/api 的下载量有多少?

根据 npm 官方下载统计,@djangocfg/api 在 2026/10/13 – 2026/11/11 这 30 天内被下载 18,939 次,日均约 631 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@djangocfg/api 还在维护吗?

最新版本 2.1.655 发布于 2026/11/12(今天);至今共发布 672 个版本,其中过去 12 个月发布了 630 个;首次发布于 2025/10/13。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。