
翻译:
服务器端 Next.js 公用事业: OG 图像、站点地图、健康检查、i18n、PWA、导航和配置
部分 强哥CFG 现代Django框架,用于建立生产准备的SaaS应用程序。 全体 @djangocfg/* 软件包被设计成可以一起工作,提供类型安全配置,实时功能,以及箱外美丽的管理员界面.
概览
@djangocfg/nextjs 为建于 Django-CFG 上方的 Next.js 应用程序提供服务器侧式服务.
说明: 客户端组件(合法页面、错误页面、重定向组件)在
@djangocfg/layouts。 。 。 .
特征
- 页面元数据+ OG 图像 – 一个完整页面元数据厂:标题,cononical + hreflang, OpenGraph, Twitter,图标(
@djangocfg/nextjs/og-image(中文(简体) ) - i18n (英语) ——与路由,中件,和组件的完全下接集成
- 巴布亚新几内亚 零配置服务工作者和清单
- Base Next.js 配置 ——可重复使用
createBaseNextConfig()单体工厂 - 安全头+CSP • 基线内容-安全政策和每条路线的硬化信头,深知(见下文)
- 巴布亚新几内亚 ——显示,取景口,图标,安装即时,棋子如何相合——看
@docs/PWA_APP_SETUP.md - 语句 ——由相接站点地图索引支撑
django_cfg.modules.django_sitemap(手提电脑2M+ URL) - 健康检查 - 生产准备的健康监测终点
- 导航 – 路由定义,菜单生成,以及活动状态帮助器
- AI 文档 ——通过MCP服务器和CLI搜索DjangoCFG文件
安装
npm install @djangocfg/nextjs
# or
pnpm add @djangocfg/nextjs
# or
yarn add @djangocfg/nextjs
快速启动
AI 文档搜索
从终端搜索 DjangoCFG 文件:
# CLI (works anywhere via npx)
npx @djangocfg/nextjs ai-docs search "database configuration"
npx @djangocfg/nextjs ai-docs mcp
或使用类型脚本 API:
import { search, getDocs, getMcpConfig } from '@djangocfg/nextjs/ai';
// Search documentation
const results = await search('database configuration');
results.forEach(r => console.log(r.title, r.url));
// Get formatted docs
const docs = await getDocs('How to configure PostgreSQL?');
// Get MCP server config for AI assistants
const config = getMcpConfig();
MCP AI 助理服务器
添加到您的 AI 助手配置 :
{
"mcpServers": {
"djangocfg-docs": {
"url": "https://mcp.djangocfg.com/mcp"
}
}
}
Base Next.js 配置
为您所有 Next.js 工程创建可重复使用的基础配置 :
// next.config.ts
import { createBaseNextConfig } from '@djangocfg/nextjs/config';
import bundleAnalyzer from '@next/bundle-analyzer';
const withBundleAnalyzer = bundleAnalyzer({
enabled: process.env.ANALYZE === 'true',
});
export default withBundleAnalyzer(createBaseNextConfig({
// Base path for static builds
basePath: process.env.NEXT_PUBLIC_STATIC_BUILD === 'true' ? '/cfg/admin' : undefined,
// Add custom transpile packages
transpilePackages: ['my-custom-package'],
// Custom webpack configuration (called after base webpack logic)
webpack: (config, options) => {
// Your custom webpack rules
return config;
},
}));
安全头和CSP
createBaseNextConfig() 添加基线安全头 每条路线 调出
框中——不需要设置:
Content-Security-Policy——实事求是的基线,堵住高价值 注射向量(object-src 'none', (中文(简体) ),base-uri 'self', (中文(简体) ),form-action 'self', (中文(简体) ),frame-ancestors)同时保留内置/eval脚本为Next.js应用程序需要. 发觉:connect-src编号 :img-src允许http:编号 :ws:促进发展(a) 本地的Django, 加上任何WebSocket 传送应用程序本身) 改为https:编号 :wss:只有生产.X-Content-Type-Options: nosniff, (中文(简体) ),Referrer-Policy: strict-origin-when-cross-originX-Frame-Options: DENY(或SAMEORIGIN何时allowIframeFrom设置)
一个完全严格的非ce基 script-src 是一个计划的后续行动( 需要中间软件 +
(b) 请求非ce)。 要允许 Iframe 嵌入, 通过 allowIframeFrom: ['https://example.com']。 。 。 .
PWA (进步网络应用)
零配置 PWA - 出局了! - 为什么? - Works out of the box! 服务工作者和离线支助自动包括在内.
1. 创建清单
// app/manifest.ts
import { createManifest, createScreenshots } from '@djangocfg/nextjs/config';
import { settings } from '@core/settings';
export default createManifest({
name: settings.app.name,
description: settings.app.description,
themeColor: '#ffffff',
backgroundColor: '#000000',
icons: {
logo192: settings.app.icons.logo192,
logo384: settings.app.icons.logo384,
logo512: settings.app.icons.logo512,
},
// Optional: Add screenshots for Richer PWA Install UI
// IMPORTANT: Image dimensions must match sizes parameter!
// screenshots: createScreenshots([
// '/screenshots/desktop-1920x1080.png', // Wide: 1920x1080
// '/screenshots/mobile-390x844.png', // Narrow: 390x844
// ]),
});
2. 添加显示的元数据
// app/layout.tsx
import { createManifestMetadata } from '@djangocfg/nextjs/config';
export const metadata = {
...createManifestMetadata({
name: 'My App',
themeColor: '#000000',
}),
};
就这样! PWA现已投入生产。 生成的文件 :
/manifest.webmanifest- 从app/manifest.ts/sw.js- 服务人员(生产中自动产生)/workbox-*.js- 工作箱运行时间
自定义 (可选) :
// next.config.ts
export default createBaseNextConfig({
pwa: {
dest: 'public',
disable: process.env.NODE_ENV === 'development', // Disable in dev
fallbacks: {
document: '/_offline', // Offline page
},
runtimeCaching: [
// Custom caching rules
...defaultRuntimeCaching,
createApiCacheRule('https://api.example.com'),
],
},
});
见 巴布亚新几内亚 为完整的向导.
i18n (国际化)
为多语种 Next.js apps 完全的下集成.
重要内容: 使用子路径导入来避免服务器组件中的回放背景问题 :
@djangocfg/nextjs/i18n- 只有类型@djangocfg/nextjs/i18n/routing- 说吧routing, (中文(简体) ),createRouting, (中文(简体) ),generateLocaleParams@djangocfg/nextjs/i18n/client- 说吧I18nProvider,钩子@djangocfg/nextjs/i18n/components- 说吧LocaleSwitcher
1. 创建中件( 代理. ts)
// proxy.ts (or middleware.ts)
import createMiddleware from 'next-intl/middleware';
import { routing } from '@djangocfg/nextjs/i18n/routing';
export default createMiddleware(routing);
export const config = {
matcher: ['/((?!api|_next|_vercel|.*\\..*).*)',],
};
2. 创建 i18n 请求配置
// i18n/request.ts
import { getRequestConfig } from 'next-intl/server';
import { en, ru, ko } from '@djangocfg/i18n/locales';
import { mergeTranslations } from '@djangocfg/i18n/utils';
const locales = {
en: mergeTranslations(en, { app: appEn }),
ru: mergeTranslations(ru, { app: appRu }),
ko: mergeTranslations(ko, { app: appKo }),
};
export default getRequestConfig(async ({ requestLocale }) => {
let locale = await requestLocale;
if (!locale || !(locale in locales)) locale = 'en';
return {
locale,
messages: locales[locale],
timeZone: 'UTC',
};
});
3. 在布局中使用
// app/[locale]/layout.tsx
import { getMessages } from 'next-intl/server';
import { I18nProvider } from '@djangocfg/nextjs/i18n/client';
import { routing, generateLocaleParams } from '@djangocfg/nextjs/i18n/routing';
export function generateStaticParams() {
return generateLocaleParams();
}
export default async function LocaleLayout({ children, params }) {
const { locale } = await params;
const messages = await getMessages();
return (
<I18nProvider locale={locale} messages={messages}>
{children}
</I18nProvider>
);
}
4. 使用组件翻译
'use client';
import { useTranslations } from 'next-intl';
function MyComponent() {
const t = useTranslations('app');
return <h1>{t('title')}</h1>;
}
共享地方饼干( 多个主机, 一个家庭)
NEXT_LOCALE 由 代理服务器 (单位:千美元)createProxy → shareLocaleCookie和通过 useChangeLocale 在浏览器中,从不渲染。 服务器组件从 URL 片段读取了本地语, 所以 cookie 无法改变 SSR 的成份; 它只能决定空地 / 调头 与 Domain=<registrable domain> 家里的每个宿主都会发出同样的价值;只宿主的双胞胎已经过期了,所以无法遮盖. 覆盖域猜测 NEXT_PUBLIC_COOKIE_DOMAIN。 。 。 .
其代价,以及保持安保部门安全的规则:
- 设置 cookie 的响应默认不会被 CDN 缓存 。 代理服务器只设定在下一集( 光路访问或开关) 时, 而不是在每个页面视图上; 保留它而不添加
Set-Cookie到静态页面. - 从不读
NEXT_LOCALE在服务器组件中( e)cookies()使路由动态。 拿着locale从params。 。 。 . - SEO 站点(每个主机1个语言,索引)保存
localeCookie: false;共享仅适用于登录后的应用家庭. - 如果这曾经引起麻烦,倒背就根本不是饼干: 地产住在URL,家庭切换器用同个地产前缀链接到兄弟会主机.
本地切换器
聪明的包装 @djangocfg/layouts 带有下接钩的本地化交换器 :
import { LocaleSwitcher } from '@djangocfg/nextjs/i18n/components';
// Basic usage (automatically gets locale from next-intl)
<LocaleSwitcher />
// With custom locales (override routing config)
<LocaleSwitcher locales={['en', 'ru']} />
// With custom labels and styling
<LocaleSwitcher
labels={{ en: 'English', ru: 'Русский' }}
variant="outline"
size="sm"
/>
说明: 此组件包
@djangocfg/layouts语言交换器useLocaleSwitcher()钩. 对于通过道具接受地语数据的演示文稿版本,使用LocaleSwitcher从@djangocfg/layouts直接说.
单一登录主机( 可选)
一个登录主机( O)auth.<apex>对所有子域: auth={{ sso: true }} 打开 BaseApp 加上,避免闪出
保护页面,此代理/中间软件。 开始吧 localhost; 登录主机本身从未方向化.
// proxy.ts (or middleware.ts)
import { createSsoMiddleware } from '@djangocfg/nextjs/auth/middleware';
export const proxy = createSsoMiddleware({ protect: ['/private'], allow: ['/private/shared'] });
主持人是 auth. + 可注册域 NEXT_PUBLIC_SITE_URL (覆盖 : authHost 选项或
NEXT_PUBLIC_AUTH_HOST) (中文(简体) ). 它只检查共享饼干是否存在;API决定它是否有效. 写出来
使用 i18n 代用符,先返回方向(参见 apps/demo/proxy.ts。设置和设置 next 规则:
一个子域的登录主机。 。 。 .
子项目生成
与 django_cfg.modules.django_sitemap。 。 。 .
由打出JSON合同支持: Django 溪流键盘插入块,
下一个是本地人 generateSitemaps() 将每个块变成一个 XML 文件
加自动生成的 <sitemapindex> 时间 /sitemap.xml处理
目录高达Google 的 50,000- URLs – file 封顶,但没有实现
前端的数据.
// app/sitemap.ts
import { createDjangoSitemap } from '@djangocfg/nextjs/sitemap';
const { generateSitemaps, sitemap } = createDjangoSitemap({
host: process.env.NEXT_PUBLIC_SITE_URL!,
apiUrl: process.env.NEXT_PUBLIC_API_URL, // optional — omit for static-only
staticRoutes: [
{ path: '/', changeFrequency: 'daily', priority: 1.0 },
{ path: '/catalog', changeFrequency: 'daily', priority: 0.9 },
],
});
export { generateSitemaps, sitemap as default };
export const revalidate = 3600;
// app/robots.ts
import { createRobots } from '@djangocfg/nextjs/sitemap';
export default createRobots({
host: process.env.NEXT_PUBLIC_SITE_URL!,
disallow: ['/account/', '/auth', '/api/'],
});
见 src/sitemap/README.md 全文
后端 QQ 前端整合指南,包括 Django 源
注册、缓存层和部署说明.
健康检查终点
建立健康监测终点:
// app/healthz/route.ts
import { createHealthHandler } from '@djangocfg/nextjs/health';
export const GET = createHealthHandler({
version: process.env.NEXT_PUBLIC_APP_VERSION || '1.0.0',
checks: [
{
name: 'database',
check: async () => {
// Check database connection
return await checkDatabase();
},
},
],
});
页面元数据+ OG 图像
每个应用程序一个工厂建立完整页面 Metadata (标题,打开Graph,推特,
canonical + hreflang,图标). OG 图像由单个选择 og 字段 -
默认的静态品牌图像, 或者精确的 URL :
// app/_core/metadata.ts — bind once
import { makeMetadataFactory } from '@djangocfg/nextjs/og-image'
export const createMetadata = makeMetadataFactory({
name: settings.app.name,
description: settings.app.description,
siteUrl: settings.app.siteUrl,
ogImage: settings.app.media.ogimage,
locales: LOCALES,
})
// landing page → static brand image (default)
export const metadata = createMetadata({ title: 'Pricing', path: '/pricing' })
// content page with its own image
export const metadata = createMetadata({ title: p.name, path, og: { image: p.image } })
每页卡片,加一张 opengraph-image 路径 — Next.js find it
以文件名表示,其输出超过任何工厂设置,所以工厂
没有自己的"动态"案例.
导航工具
定义路线并生成导航菜单 :
import { defineRoute, routesToMenuItems } from '@djangocfg/nextjs/navigation';
const routes = [
defineRoute('/dashboard', { title: 'Dashboard' }),
defineRoute('/settings', { title: 'Settings' }),
];
const menuItems = routesToMenuItems(routes);
客户端组件
客户端组件(合法页面、错误页、重定向组件)可用 @djangocfg/layouts数字 :
// Legal pages
import { PrivacyPage, TermsPage } from '@djangocfg/layouts/pages/legal';
// Error pages
import { ErrorLayout } from '@djangocfg/layouts/components/errors';
// Redirect component
import { RedirectPage } from '@djangocfg/layouts/components/RedirectPage';
出口
| 路径 | 说明 |
|---|---|
@djangocfg/nextjs | 主要出口(所有模块) |
@djangocfg/nextjs/i18n | 仅类型 (服务器组件的安全) |
@djangocfg/nextjs/i18n/routing | routing, (中文(简体) ), createRouting, (中文(简体) ), generateLocaleParams, (中文(简体) ), DEFAULT_LOCALES, (中文(简体) ), DEFAULT_LOCALE |
@djangocfg/nextjs/i18n/client | I18nProvider,钩子('use client'(中文(简体) ) |
@djangocfg/nextjs/i18n/server | 服务器侧i18n公用事业 |
@djangocfg/nextjs/i18n/components | LocaleSwitcher (单位:千美元)'use client'(中文(简体) ) |
@djangocfg/nextjs/i18n/proxy | createProxy 用于中间软件 |
@djangocfg/nextjs/i18n/navigation | Link, (中文(简体) ), redirect, (中文(简体) ), usePathname, (中文(简体) ), useRouter |
@djangocfg/nextjs/auth | 服务器侧共享会话 cookie : serverAuthHeaders, (中文(简体) ), getServerAccessToken, (中文(简体) ), hasServerSession |
@djangocfg/nextjs/auth/middleware | createSsoMiddleware: 单一登录主机( 受保护路径的签名访问者前往) auth.<apex>/auth?next=… 在任何变异之前; 边缘安全) |
@djangocfg/nextjs/ai | AI 文档搜索和 MCP 配置 |
@djangocfg/nextjs/config | Base Next.js 配置厂 |
@djangocfg/nextjs/pwa | PWA客户公用事业(工人登记) |
@djangocfg/nextjs/pwa/worker | 服务工人创造者 |
@djangocfg/nextjs/sitemap | 具有 i18n hreflang 支持的 siteap 生成 |
@djangocfg/nextjs/health | 体检员 |
@djangocfg/nextjs/og-image | 页面元数据厂 — 标题, canonical + hreflang, OpenGraph, Twitter, 图标 |
@djangocfg/nextjs/navigation | 路线定义、菜单生成、导航帮助 |
API 参考
基础配置
createBaseNextConfig(options)
创建具有标准 DjangoCFG 设置的可重复使用的 Base Next.js 配置 .
createBaseNextConfig({
basePath?: string; // Base path for static builds
transpilePackages?: string[]; // Additional packages to transpile
optimizePackageImports?: string[]; // Additional packages to optimize
webpack?: (config, options) => config; // Custom webpack configuration
experimental?: NextConfig['experimental']; // Custom experimental options
env?: Record<string, string>; // Custom environment variables
// ... any other NextConfig options
})
特征 :
- 自动 dev/生产优化
- 文件系统缓存以更快地重建
- 静态构建的压缩插件( Gzip + Brotli)
- 单列波标准转接包
- 类型安全配置合并
i18n (英语)
需要从亚行导入 - 正确的导入路径见下表.
DEFAULT_LOCALES 编号 : DEFAULT_LOCALE
所有17个都支持地语和默认地语常数.
import { DEFAULT_LOCALES, DEFAULT_LOCALE } from '@djangocfg/nextjs/i18n/routing';
DEFAULT_LOCALES // ['en', 'ru', 'ko', 'ja', 'de', 'fr', 'zh', 'it', 'es', 'nl', 'ar', 'tr', 'pt-BR', 'pl', 'sv', 'no', 'da']
DEFAULT_LOCALE // 'en'
用于 locales.config.ts 与软件包同步 :
// i18n/locales.config.ts
export { DEFAULT_LOCALES as LOCALES, DEFAULT_LOCALE } from '@djangocfg/nextjs/i18n/routing';
export type { LocaleCode as AppLocale } from '@djangocfg/nextjs/i18n';
routing
包含全部 17 个地块和默认地块的默认路由配置 'en'。 。 。 .
import { routing } from '@djangocfg/nextjs/i18n/routing';
routing.locales // ['en', 'ru', 'ko', 'ja', ...]
routing.defaultLocale // 'en'
createRouting(config?)
创建自定义路由配置 .
import { createRouting } from '@djangocfg/nextjs/i18n/routing';
const routing = createRouting({
locales: ['en', 'de', 'fr'],
defaultLocale: 'en',
localePrefix: 'always', // 'always' | 'as-needed' | 'never'
});
I18nProvider
下一步整合的供应商部分(客户部分).
import { I18nProvider } from '@djangocfg/nextjs/i18n/client';
<I18nProvider locale="en" messages={messages}>
{children}
</I18nProvider>
过 locales (设置的应用船) 所以 useLocales() 编号 : useLocaleSwitcher() 报告它;没有它,它们就会回到内置的17个本地列表.
LocaleSwitcher
包装的智能地盘切换器 @djangocfg/layouts 带下通钩的本地化开关.
import { LocaleSwitcher } from '@djangocfg/nextjs/i18n/components';
// Automatically gets locale from next-intl routing
<LocaleSwitcher />
// With custom options
<LocaleSwitcher
locales={['en', 'ru']} // Override available locales
labels={{ en: 'EN', ru: 'RU' }} // Custom locale labels
variant="outline"
size="sm"
showIcon={true}
className="w-full"
/>
道具 (续) @djangocfg/layouts 本地开关程序 :
| Prop | 类型 | 默认 | 说明 |
|---|---|---|---|
locales | string[] | 从路由 | 覆盖可用的本地地址 |
labels | Record<string, string> | 内建 | 自定义地盘标签 |
showCode | boolean | false | 显示带有标签的地盘代码 |
variant | 'ghost' | 'outline' | 'default' | 'ghost' | 按钮变体 |
size | 'sm' | 'default' | 'lg' | 'icon' | 'sm' | 按钮大小 |
showIcon | boolean | true | 显示地球图示 |
语句
createSitemapHandler(options)
为 sitemap 生成创建 Next.js 路由处理器, 并有可选的 i18n 支持 .
createSitemapHandler({
siteUrl: string;
staticPages?: SitemapUrl[];
dynamicPages?: SitemapUrl[] | (() => Promise<SitemapUrl[]>);
cacheControl?: string;
// i18n support
i18n?: {
locales: string[]; // e.g., ['en', 'ru', 'ko']
defaultLocale: string; // e.g., 'en'
};
})
何时 i18n 规定如下:
- 每个地块的URL都会被扩展(例如,
/about→/en/about, (中文(简体) ),/ru/about, (中文(简体) ),/ko/about(中文(简体) ) xhtml:link元素为hreflang正在为 SIO 添加x-default指向默认区域
卫生
createHealthHandler(config)
创建健康检查路径处理器.
createHealthHandler({
version?: string;
checks?: Array<{ name: string; check: () => Promise<boolean> }>;
customData?: Record<string, any>;
})
页面元数据 + OG 图像
@djangocfg/nextjs/og-image 构建完整的页面元数据:标题调试,
canonical + hreflang 候补,OpenGraph,Twitter卡和图标.
见 src/og-image/README.md 完整文档 og
轴, SiteMetaConfig编号 :PageMeta 字段).
makeMetadataFactory(config) - 建议
带子 a SiteMetaConfig 一次;返回每页的工厂。 OG 图像由
单曲 og 字段 : 'static' (默认) { image, alt? }。 。 。 .
import { makeMetadataFactory } from '@djangocfg/nextjs/og-image'
export const createMetadata = makeMetadataFactory({
name: 'CMDOP', description: '…', siteUrl: 'https://cmdop.com',
ogImage: '/static/ogimage.png', locales: LOCALES,
})
export const metadata = createMetadata({ title: 'About', path: '/about' }) // brand image
export const metadata = createMetadata({ title: p.name, og: { image: p.image } })
每页卡片
使用下一张.js的 opengraph-image 备案公约——但注意它只适用于
元数据叶 openGraph.images 未设. createMetadata 总是设置它,所以
除非页面从元数据中删除密钥
工厂回来了。 见 src/og-image/README.md。 。 。 .
低级(逃生舱)
resolveOgImage(spec, staticUrl, fallbackTitle) 这是 OgSpec 决策点;
extractTitle(metadata) 读取 Next.js 标题形状的平面标题。 多数
页面使用 createMetadata 永远不要碰这些.
导航
defineRoute(path, metadata, config?)
定义带有元数据的路由.
defineRoute('/dashboard', {
title: 'Dashboard',
description: 'Dashboard overview',
}, {
basePath: '/admin',
isStaticBuild: false,
})
isActive(current, target, allRoutes?)
检查当前是否有一条路由活动 .
isActive('/admin/dashboard', '/admin/dashboard') // true
isActive('/admin/dashboard/settings', '/admin/dashboard') // true
isActive('/admin/dashboard', '/admin/settings') // false
routesToMenuItems(routes)
将路由定义转换为菜单项.
const menuItems = routesToMenuItems(allRoutes);
所需资源
- Next.js QQ 13.0.0 (App路由器) (英语)
- 反应 QQ 18.0.0
- 类型脚本QQ 5.0.0
同伴依赖关系
next- 下一个框架(^15.5.7)
文档
备有文件全文 djangocfg.com (中文(简体) )
捐款
欢迎提出问题和拉动请求 GitHub 图像
许可证
麻省理工学院 - 看 自由主义 详情