nextjs-16-complete-guide by fernandofuc/nextjs-claude-setup
npx skills add https://github.com/fernandofuc/nextjs-claude-setup --skill nextjs-16-complete-guide全面参考 Next.js 16 的革命性特性:使用 "use cache" 的缓存组件、作为默认打包器的稳定 Turbopack、proxy.ts 架构、DevTools MCP 集成以及 React Compiler 支持。
Next.js 15 是过渡阶段 - 异步 API、实验性 Turbopack、不断变化的缓存默认值。Next.js 16 是成果兑现 - 一切都变得稳定、快速且可用于生产环境。
| 特性 | Next.js 15 | Next.js 16 |
|---|---|---|
| 打包器 | Webpack (默认), Turbopack (可选测试版) | Turbopack (默认, 稳定) |
| 缓存 | 隐式,令人困惑的默认值 | 使用 "use cache" 显式控制 |
| 网络层 | middleware.ts (边缘运行时) |
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
| proxy.ts (Node.js 运行时) |
| DevTools | 基本错误信息 | 集成 MCP 进行 AI 调试 |
| React Compiler | 实验性 | 稳定,可用于生产环境 |
| 性能 | 基准 | 构建速度提升 2-5 倍,Fast Refresh 速度提升 10 倍 |
Next.js 15 中的问题:
Next.js 16 中的解决方案:
// 在 next.config.ts 中启用
const nextConfig = {
cacheComponents: true,
};
export default nextConfig;
使用模式:
// app/dashboard/page.tsx
import { Suspense } from 'react';
// 此组件缓存其输出
async function UserMetrics() {
'use cache'; // 🎯 显式缓存
const metrics = await fetchMetrics(); // 缓存结果
return <MetricsCard data={metrics} />;
}
// 此组件保持动态
async function LiveBalance() {
const balance = await fetchBalance(); // 始终获取最新数据
return <BalanceWidget balance={balance} />;
}
export default function Dashboard() {
return (
<div>
<Suspense fallback={<LoadingMetrics />}>
<UserMetrics /> {/* 已缓存,即时加载 */}
</Suspense>
<LiveBalance /> {/* 动态,实时 */}
</div>
);
}
为何重要:
缓存粒度:
// 缓存整个页面
export default async function Page() {
'use cache';
return <PageContent />;
}
// 缓存单个组件
async function ExpensiveWidget() {
'use cache';
return <Chart data={await getData()} />;
}
// 缓存函数结果
async function getStats() {
'use cache';
return await database.query('...');
}
性能数据 (官方 Vercel 基准测试):
无需配置:
// next.config.ts
// Turbopack 现在是默认值 - 无需配置!
选择退出 (如果需要):
# 改用 Webpack
next build --webpack
文件系统缓存 (测试版):
// next.config.ts
const nextConfig = {
experimental: {
turbopackFileSystemCacheForDev: true, // 更快的重启
},
};
为何重要:
您会注意到:
# 之前 (Webpack)
✓ Compiled in 4.2s
# 之后 (Turbopack)
✓ Compiled in 0.4s # 快 10 倍
变化:
# 旧版 (Next.js 15)
middleware.ts # 边缘运行时,令人困惑
# 新版 (Next.js 16)
proxy.ts # Node.js 运行时,显式
迁移示例:
// 旧版: middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
return NextResponse.redirect(new URL('/home', request.url));
}
export const config = {
matcher: '/about/:path*',
};
// 新版: proxy.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export default function proxy(request: NextRequest) { // 更改了函数名
return NextResponse.redirect(new URL('/home', request.url));
}
export const config = {
matcher: '/about/:path*',
};
关键变化:
middleware.ts → proxy.tsexport function middleware → export default function proxy为何重要:
功能: Next.js 16 集成了模型上下文协议 (MCP),使 AI 代理能够:
为何重要:
用例:
您:"为什么这个页面没有缓存?"
AI 代理 (使用 MCP):
- 读取服务器日志
- 查看路由配置
- 检查缓存头
- 了解 Next.js 16 缓存规则
→ "您的组件中缺少 'use cache' 指令"
集成: 自动与 Claude Code、Cursor 和其他支持 MCP 的工具配合使用。
功能: 自动记忆化组件 - 不再需要手动使用 useMemo、useCallback、React.memo。
设置:
npm install babel-plugin-react-compiler@latest
// next.config.ts
const nextConfig = {
reactCompiler: true, // 从实验性移至稳定
};
之前 (手动优化):
// 您必须在各处这样做
const MemoizedComponent = React.memo(function Component({ data }) {
const processed = useMemo(() => processData(data), [data]);
const handleClick = useCallback(() => {
console.log(processed);
}, [processed]);
return <div onClick={handleClick}>{processed}</div>;
});
之后 (React Compiler 自动完成):
// 只需编写代码,编译器自动优化
function Component({ data }) {
const processed = processData(data); // 自动记忆化
const handleClick = () => { // 自动记忆化
console.log(processed);
};
return <div onClick={handleClick}>{processed}</div>;
}
为何重要:
# 最低要求: Node.js 20.9+
# Next.js 15: Node.js 18 可用
# Next.js 16: 不再支持 Node.js 18
// ❌ 旧版 (Next.js 15)
export default function Page({ params, searchParams }) {
const id = params.id; // 同步
}
// ✅ 新版 (Next.js 16)
export default async function Page({ params, searchParams }) {
const { id } = await params; // 必须 await
const { query } = await searchParams;
}
// ❌ 旧版
import { cookies } from 'next/headers';
export function MyComponent() {
const token = cookies().get('token'); // 同步
}
// ✅ 新版
import { cookies } from 'next/headers';
export async function MyComponent() {
const cookieStore = await cookies(); // 必须 await
const token = cookieStore.get('token');
}
// ❌ 旧版
revalidateTag('posts');
// ✅ 新版
revalidateTag('posts', 'max'); // 选项: 'max', 'hours', 'days'
# 必需的迁移
mv middleware.ts proxy.ts
# 更新函数名
export default function proxy(request) { ... }
next lint 命令 - 已移除# 检查当前版本
node --version # 应为 20.9+
npm list next # 当前 Next.js 版本
npm list react # React 版本
# 升级到最新的 Next.js 16
npm install next@latest react@latest react-dom@latest
# 运行 codemod (自动处理大多数更改)
npx @next/codemod@canary upgrade latest
更新 next.config:
// next.config.ts
import type { NextConfig } from 'next';
const nextConfig: NextConfig = {
// 启用缓存组件
cacheComponents: true,
// 启用 React Compiler
reactCompiler: true,
// 可选: 文件系统缓存
experimental: {
turbopackFileSystemCacheForDev: true,
},
};
export default nextConfig;
重命名 middleware:
# 如果您有 middleware.ts
git mv middleware.ts proxy.ts
# 在 proxy.ts 中更新函数名
export default function proxy(request: NextRequest) {
// 您的逻辑
}
更新异步 API:
// 在代码库中搜索:
// - params.
// - searchParams.
// - cookies()
// - headers()
// - draftMode()
// 在每个前面添加 await
# 开发环境
npm run dev # 应自动使用 Turbopack
# 生产构建
npm run build # 应快 2-5 倍
# 运行测试
npm test
# 验证生产环境中的 Node.js 版本
# 部署到 Vercel/平台
# 监控前 24 小时的错误
npx create-next-app@latest my-app
# 自动使用 Next.js 16, Turbopack, TypeScript, Tailwind
// ✅ 良好: 缓存昂贵、不频繁更改的数据
async function MonthlyReport() {
'use cache';
return await generateReport();
}
// ❌ 不良: 不要缓存用户特定的实时数据
async function CurrentBalance() {
'use cache'; // 错误!这应该是新鲜的
return await getUserBalance();
}
# Next.js 16 显示详细计时
npm run build
# 示例输出:
Route (app) Size First Load JS
┌ ○ / 142 B 87.2 kB
├ ○ /_not-found 142 B 87.2 kB
└ ○ /dashboard 1.23 kB 88.4 kB
Build time: 14.2s # 在 Next.js 15 中使用 Webpack 时为 57s
// 仅在遇到性能问题时启用
reactCompiler: true
npm install next@latest react@latest react-dom@latest
// next.config.ts
const nextConfig = {
cacheComponents: true, // 缓存组件
reactCompiler: true, // React Compiler
experimental: {
turbopackFileSystemCacheForDev: true, // 更快的开发重启
},
};
npm install next@latestnpx @next/codemod@canary upgrade latestmiddleware.ts → proxy.tsawaitrevalidateTag() 调用npm run buildnpm run dev总结: Next.js 16 兑现了 15 的承诺 - 一切都更快、更显式且可用于生产环境。Turbopack 成为默认,缓存可预测,AI 工具原生集成。这是在 2025 年构建现代 SaaS 应用的版本。
每周安装次数
197
仓库
首次出现
2026 年 1 月 24 日
安全审计
安装于
gemini-cli173
opencode172
codex166
github-copilot160
cursor153
kimi-cli133
Comprehensive reference for Next.js 16's revolutionary features: Cache Components with "use cache", stable Turbopack as default bundler, proxy.ts architecture, DevTools MCP integration, and React Compiler support.
Next.js 15 was transition phase - async APIs, experimental Turbopack, changing cache defaults. Next.js 16 is the payoff - everything becomes stable, fast, and production-ready.
| Feature | Next.js 15 | Next.js 16 |
|---|---|---|
| Bundler | Webpack (default), Turbopack (opt-in beta) | Turbopack (default, stable) |
| Caching | Implicit, confusing defaults | Explicit with "use cache" |
| Network Layer | middleware.ts (edge runtime) | proxy.ts (Node.js runtime) |
| DevTools | Basic error messages | MCP integration for AI debugging |
| React Compiler | Experimental | Stable, production-ready |
| Performance | Baseline | 2-5× faster builds, 10× faster Fast Refresh |
The Problem in Next.js 15:
The Solution in Next.js 16:
// Enable in next.config.ts
const nextConfig = {
cacheComponents: true,
};
export default nextConfig;
Usage Pattern:
// app/dashboard/page.tsx
import { Suspense } from 'react';
// This component caches its output
async function UserMetrics() {
'use cache'; // 🎯 Explicit caching
const metrics = await fetchMetrics(); // Cached result
return <MetricsCard data={metrics} />;
}
// This stays dynamic
async function LiveBalance() {
const balance = await fetchBalance(); // Always fresh
return <BalanceWidget balance={balance} />;
}
export default function Dashboard() {
return (
<div>
<Suspense fallback={<LoadingMetrics />}>
<UserMetrics /> {/* Cached, instant load */}
</Suspense>
<LiveBalance /> {/* Dynamic, real-time */}
</div>
);
}
Why This Matters:
Cache Granularity:
// Cache entire page
export default async function Page() {
'use cache';
return <PageContent />;
}
// Cache individual component
async function ExpensiveWidget() {
'use cache';
return <Chart data={await getData()} />;
}
// Cache function result
async function getStats() {
'use cache';
return await database.query('...');
}
Performance Numbers (Official Vercel Benchmarks):
No Configuration Needed:
// next.config.ts
// Turbopack is now default - no config required!
Opt-out (if needed):
# Use Webpack instead
next build --webpack
File System Caching (Beta):
// next.config.ts
const nextConfig = {
experimental: {
turbopackFileSystemCacheForDev: true, // Faster restarts
},
};
Why This Matters:
What You Notice:
# Before (Webpack)
✓ Compiled in 4.2s
# After (Turbopack)
✓ Compiled in 0.4s # 10× faster
The Change:
# Old (Next.js 15)
middleware.ts # Edge runtime, confusing
# New (Next.js 16)
proxy.ts # Node.js runtime, explicit
Migration Example:
// OLD: middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
return NextResponse.redirect(new URL('/home', request.url));
}
export const config = {
matcher: '/about/:path*',
};
// NEW: proxy.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export default function proxy(request: NextRequest) { // Changed function name
return NextResponse.redirect(new URL('/home', request.url));
}
export const config = {
matcher: '/about/:path*',
};
Key Changes:
middleware.ts → proxy.tsexport function middleware → export default function proxyWhy This Matters:
What It Does: Next.js 16 integrates Model Context Protocol (MCP) so AI agents can:
Why This Matters:
Use Case:
You: "Why is this page not caching?"
AI Agent (with MCP):
- Reads server logs
- Sees route configuration
- Checks cache headers
- Knows Next.js 16 caching rules
→ "You're missing 'use cache' directive in your component"
Integration: Works automatically with Claude Code, Cursor, and other MCP-compatible tools.
What It Does: Automatically memoizes components - no more manual useMemo, useCallback, React.memo.
Setup:
npm install babel-plugin-react-compiler@latest
// next.config.ts
const nextConfig = {
reactCompiler: true, // Moved from experimental to stable
};
Before (Manual Optimization):
// You had to do this everywhere
const MemoizedComponent = React.memo(function Component({ data }) {
const processed = useMemo(() => processData(data), [data]);
const handleClick = useCallback(() => {
console.log(processed);
}, [processed]);
return <div onClick={handleClick}>{processed}</div>;
});
After (React Compiler Does It):
// Just write code, compiler optimizes automatically
function Component({ data }) {
const processed = processData(data); // Auto-memoized
const handleClick = () => { // Auto-memoized
console.log(processed);
};
return <div onClick={handleClick}>{processed}</div>;
}
Why This Matters:
# Minimum: Node.js 20.9+
# Next.js 15: Node.js 18 worked
# Next.js 16: Node.js 18 no longer supported
// ❌ OLD (Next.js 15)
export default function Page({ params, searchParams }) {
const id = params.id; // Synchronous
}
// ✅ NEW (Next.js 16)
export default async function Page({ params, searchParams }) {
const { id } = await params; // Must await
const { query } = await searchParams;
}
// ❌ OLD
import { cookies } from 'next/headers';
export function MyComponent() {
const token = cookies().get('token'); // Synchronous
}
// ✅ NEW
import { cookies } from 'next/headers';
export async function MyComponent() {
const cookieStore = await cookies(); // Must await
const token = cookieStore.get('token');
}
// ❌ OLD
revalidateTag('posts');
// ✅ NEW
revalidateTag('posts', 'max'); // Options: 'max', 'hours', 'days'
# Required migration
mv middleware.ts proxy.ts
# Update function name
export default function proxy(request) { ... }
next lint command - Removed# Check current versions
node --version # Should be 20.9+
npm list next # Current Next.js version
npm list react # React version
# Upgrade to latest Next.js 16
npm install next@latest react@latest react-dom@latest
# Run codemod (handles most changes automatically)
npx @next/codemod@canary upgrade latest
Update next.config:
// next.config.ts
import type { NextConfig } from 'next';
const nextConfig: NextConfig = {
// Enable Cache Components
cacheComponents: true,
// Enable React Compiler
reactCompiler: true,
// Optional: File system caching
experimental: {
turbopackFileSystemCacheForDev: true,
},
};
export default nextConfig;
Rename middleware:
# If you have middleware.ts
git mv middleware.ts proxy.ts
# Update function name in proxy.ts
export default function proxy(request: NextRequest) {
// Your logic
}
Update async APIs:
// Search codebase for:
// - params.
// - searchParams.
// - cookies()
// - headers()
// - draftMode()
// Add await before each
# Development
npm run dev # Should use Turbopack automatically
# Production build
npm run build # Should be 2-5× faster
# Run tests
npm test
# Verify Node.js version in production
# Deploy to Vercel/platform
# Monitor for errors in first 24h
npx create-next-app@latest my-app
# Automatically uses Next.js 16, Turbopack, TypeScript, Tailwind
// ✅ Good: Cache expensive, infrequent-changing data
async function MonthlyReport() {
'use cache';
return await generateReport();
}
// ❌ Bad: Don't cache user-specific real-time data
async function CurrentBalance() {
'use cache'; // Wrong! This should be fresh
return await getUserBalance();
}
# Next.js 16 shows detailed timing
npm run build
# Example output:
Route (app) Size First Load JS
┌ ○ / 142 B 87.2 kB
├ ○ /_not-found 142 B 87.2 kB
└ ○ /dashboard 1.23 kB 88.4 kB
Build time: 14.2s # Was 57s in Next.js 15 with Webpack
// Only if you have performance issues
reactCompiler: true
npm install next@latest react@latest react-dom@latest
// next.config.ts
const nextConfig = {
cacheComponents: true, // Cache Components
reactCompiler: true, // React Compiler
experimental: {
turbopackFileSystemCacheForDev: true, // Faster dev restarts
},
};
npm install next@latestnpx @next/codemod@canary upgrade latestmiddleware.ts → proxy.tsawait to params/searchParams/cookies/headersrevalidateTag() calls with cacheLifenpm run buildnpm run devSummary: Next.js 16 delivers on the promises of 15 - everything is faster, more explicit, and production-ready. Turbopack is default, caching is predictable, and AI tooling is native. This is the version to build modern SaaS applications on in 2025.
Weekly Installs
197
Repository
First Seen
Jan 24, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
gemini-cli173
opencode172
codex166
github-copilot160
cursor153
kimi-cli133
Flutter应用架构设计指南:分层结构、数据层实现与最佳实践
4,100 周安装