随着 Next.js 13+ 全面拥抱 App Router 架构,传统的 Pages Router 配置方式已逐步演进。App Router 带来了更强大的 React Server Components(RSC)、流式 SSR、内置数据获取等能力,同时也对 next.config.js
的使用提出了新的最佳实践。
下面将为你提供一份专为 App Router 设计的企业级 next.config.js
配置模板,涵盖:
- 基础优化(SWC、严格模式)
- 环境变量管理
- 图片与字体优化
- 路径别名(Webpack)
- App Router 兼容的国际化方案说明
- API 代理(Rewrites)
- 安全 Headers
- 构建追踪与打包分析
✅ 适用场景:Next.js 13+ App Router、中大型项目、多环境部署、微前端、安全合规要求高的企业应用。
📦 完整配置模板(App Router 专用)
js
/** @type {import('next').NextConfig} */
const path = require('path');
const isProd = process.env.NODE_ENV === 'production';
const nextConfig = {
// ======================
// 1. 启用 App Router(Next.js 13+ 默认开启,显式声明更清晰)
// ======================
experimental: {
appDir: true, // 启用 App Router(Next.js 14+ 可省略)
},
// ======================
// 2. 基础优化
// ======================
reactStrictMode: true, // 检测潜在问题
swcMinify: true, // 使用 SWC 压缩,构建更快
// ======================
// 3. 环境变量(仅非敏感、需暴露给客户端的变量)
// ======================
env: {
NEXT_PUBLIC_APP_NAME: 'MyEnterpriseApp',
NEXT_PUBLIC_API_BASE_URL: isProd
? 'https://api.prod.example.com'
: 'https://api.staging.example.com',
NEXT_PUBLIC_APP_ENV: process.env.NEXT_PUBLIC_APP_ENV || 'development',
},
// ======================
// 4. 图片优化(next/image 依赖)
// ======================
images: {
domains: [
'images.unsplash.com',
'cdn.yourcompany.com',
'res.cloudinary.com',
'avatars.githubusercontent.com',
],
formats: ['image/avif', 'image/webp'],
deviceSizes: [640, 750, 828, 1080, 1200, 1920],
minimumCacheTTL: 60 * 60 * 24 * 30, // 30天缓存
},
// ======================
// 5. 字体优化(自动内联 Google Fonts,防 FOIT)
// ======================
optimizeFonts: true,
// ======================
// 6. Webpack 路径别名(提升代码可读性)
// ======================
webpack(config) {
config.resolve.alias = {
...config.resolve.alias,
'@': path.resolve(__dirname, './src'),
'@components': path.resolve(__dirname, './src/components'),
'@lib': path.resolve(__dirname, './src/lib'),
'@hooks': path.resolve(__dirname, './src/hooks'),
};
return config;
},
// ======================
// 7. 路由重写(Rewrites)------ 用于 API 代理、微前端集成等
// ======================
async rewrites() {
return [
// 代理内部 API,避免 CORS
{
source: '/api/:path*',
destination: 'https://backend.internal.example.com/:path*',
},
// 微前端子应用集成示例
// {
// source: '/app/:name*',
// destination: '/_microfrontends/:name/index.html',
// },
];
},
// ======================
// 8. 路由重定向(Redirects)------ 旧链接迁移、A/B 测试
// ======================
async redirects() {
return [
{
source: '/old-dashboard',
destination: '/dashboard',
permanent: true, // 301 永久重定向,利于 SEO
},
{
source: '/zh',
destination: '/zh-CN',
permanent: true,
},
];
},
// ======================
// 9. 安全 Headers(防御常见 Web 攻击)
// ======================
async headers() {
return [
{
source: '/:path*', // 匹配所有路径
headers: [
{ key: 'X-DNS-Prefetch-Control', value: 'on' },
{ key: 'Strict-Transport-Security', value: 'max-age=63072000; includeSubDomains; preload' },
{ key: 'X-Frame-Options', value: 'DENY' }, // 防点击劫持
{ key: 'X-Content-Type-Options', value: 'nosniff' }, // 防 MIME 嗅探
{ key: 'Referrer-Policy', value: 'origin-when-cross-origin' },
// Content Security Policy (CSP) ------ 按实际资源调整!
// {
// key: 'Content-Security-Policy',
// value: "default-src 'self'; script-src 'self' 'unsafe-eval' cdn.example.com; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' fonts.googleapis.com;",
// },
],
},
];
},
// ======================
// 10. 构建 ID(用于 CI/CD 追踪、缓存失效)
// ======================
generateBuildId: async () => {
// 优先使用 Git Commit Hash(推荐)
return process.env.VERCEL_GIT_COMMIT_SHA || process.env.BUILD_ID || Date.now().toString();
},
// ======================
// 11. 输出目录与部署配置(按需启用)
// ======================
// basePath: '/my-app', // 子目录部署,如 example.com/my-app
// assetPrefix: 'https://cdn.example.com/_next', // CDN 资源前缀
// ======================
// 12. 兼容性:禁用 ETag(某些安全审计要求)
// ======================
generateEtags: false,
};
// ======================
// 13. 可选:打包分析(Bundle Analyzer)
// ======================
// 安装:npm install @next/bundle-analyzer --save-dev
// 使用:ANALYZE=true npm run build
/*
const withBundleAnalyzer = require('@next/bundle-analyzer')({
enabled: process.env.ANALYZE === 'true',
});
module.exports = withBundleAnalyzer(nextConfig);
*/
module.exports = nextConfig;
🔍 关键配置项详解(App Router 适配版)
1️⃣ 启用 App Router:experimental.appDir
js
experimental: {
appDir: true,
}
- 说明 :Next.js 13 引入 App Router 时需显式开启;Next.js 14+ 已默认启用,可省略。
- 作用 :启用
app/
目录下的新路由系统,支持:- React Server Components(RSC)
- Streaming SSR(渐进式渲染)
- 内置数据获取(
async
Server Components) - Layout 嵌套与共享状态
- 企业价值:提升首屏性能、降低客户端 JS 体积、简化数据流。
✅ 建议:新项目直接使用 App Router,旧项目可逐步迁移。
2️⃣ 环境变量:仅暴露 NEXT_PUBLIC_
前缀变量
js
env: {
NEXT_PUBLIC_API_BASE_URL: '...',
}
- 关键原则 :
- 所有
env
中的变量都会暴露给客户端! - 敏感信息(如密钥、数据库连接)绝不能放在这里。
- 所有
- 正确做法 :
- 客户端变量:使用
NEXT_PUBLIC_
前缀,定义在.env.local
- 服务端变量:直接在
.env.local
中定义(无前缀),仅在 Server Components 或 API Routes 中使用
- 客户端变量:使用
- App Router 优势 :Server Components 天然运行在服务端,可直接读取非
NEXT_PUBLIC_
变量,无需代理。
✅ 最佳实践 :
env
仅用于兼容旧代码,新项目建议直接使用.env.local
+NEXT_PUBLIC_
。
3️⃣ 国际化(i18n):App Router 的新方案
⚠️ 重要变化 :App Router 不再支持
next.config.js
中的i18n
配置!
✅ 正确做法:
-
使用 文件系统路由 实现多语言:
csharpapp/ [lang]/ page.tsx
-
结合
next-intl
、next-i18next
或自定义中间件实现:- 语言检测
- 路由重写
- 翻译加载
示例中间件(middleware.ts
):
ts
import { NextRequest, NextResponse } from 'next/server';
import { match } from '@formatjs/intl-localematcher';
import Negotiator from 'negotiator';
const locales = ['en', 'zh-CN', 'ja'];
const defaultLocale = 'en';
function getLocale(request: NextRequest): string {
const acceptLanguage = request.headers.get('accept-language');
const headers = { 'accept-language': acceptLanguage || '' };
const languages = new Negotiator({ headers }).languages();
return match(languages, locales, defaultLocale);
}
export function middleware(request: NextRequest) {
const pathname = request.nextUrl.pathname;
const pathnameIsMissingLocale = locales.every(
locale => !pathname.startsWith(`/${locale}/`) && pathname !== `/${locale}`
);
if (pathnameIsMissingLocale) {
const locale = getLocale(request);
return NextResponse.redirect(new URL(`/${locale}${pathname}`, request.url));
}
}
export const config = {
matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
};
📌 结论 :App Router 项目无需在
next.config.js
中配置 i18n,改用路由 + 中间件方案。
4️⃣ 图片与字体优化:开箱即用,但需配置
images
:配置与 Pages Router 相同,必须设置domains
白名单。optimizeFonts: true
:自动内联 Google Fonts CSS,消除布局偏移(CLS),提升 Core Web Vitals。
✅ 建议:两项均开启,对性能有显著提升。
5️⃣ Rewrites / Redirects / Headers:完全兼容
App Router 完全支持 rewrites()
、redirects()
、headers()
配置,用法与 Pages Router 一致。
- Rewrites:仍是 API 代理的最佳选择(尤其在 Vercel 部署时)
- Headers:安全加固不可或缺
- Redirects:SEO 友好迁移必备
✅ 建议 :按需配置,尤其
headers
应作为安全基线。
6️⃣ Webpack 别名:提升开发体验
js
config.resolve.alias['@'] = path.resolve(__dirname, './src');
-
作用不变:避免深层相对路径
-
配合 TypeScript :需在
tsconfig.json
中同步配置:json{ "compilerOptions": { "baseUrl": ".", "paths": { "@/*": ["src/*"], "@components/*": ["src/components/*"] } } }
✅ 建议:所有中大型项目必配。
7️⃣ 打包分析:性能优化利器
通过 @next/bundle-analyzer
可视化分析:
- 哪些依赖体积过大?
- 是否有未使用的代码?
- Client Components 是否过度使用?
⚠️ 注意:App Router 中 Server Components 不会打包到客户端,因此客户端 bundle 通常更小。
🔄 从 Pages Router 迁移注意事项
- 移除
i18n
配置 → 改用 App Router 路由 + 中间件 - 检查
getStaticProps
/getServerSideProps
→ 改为 Server Components 中的async
函数 - API Routes 位置不变 :仍位于
pages/api/
或可移至app/api/
(推荐) - 环境变量使用更安全:Server Components 可直接访问服务端变量
结语
App Router 代表了 Next.js 的未来方向,而一份与时俱进的 next.config.js
是发挥其全部潜力的基础。本文提供的配置模板兼顾了性能、安全、可维护性与现代化架构,适用于绝大多数企业级场景。
记住:配置不是一成不变的 。随着项目演进、安全策略更新、性能瓶颈出现,你的 next.config.js
也应持续迭代。