next16-expert
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chinese⚡ Skill: next16-expert
⚡ 技能:next16-expert
Description
简介
Senior specialist in the Next.js 16.1.1 and React 19.2 ecosystem. This skill focuses on the high-performance Proxy & Cache paradigm, Partial Pre-rendering (PPR), and the mandatory transition from to . It provides production-ready patterns for modern full-stack development.
middleware.tsproxy.tsNext.js 16.1.1与React 19.2生态的资深专家。本技能聚焦于高性能的Proxy & Cache范式、Partial Pre-rendering (PPR),以及从到的强制迁移,为现代全栈开发提供可用于生产环境的实践模式。
middleware.tsproxy.tsTable of Contents
目录
Quick Start
快速开始
Initialize an Elite-grade project:
bash
npx create-next-app@latest my-elite-app \
--typescript \
--tailwind \
--eslint \
--app \
--src-dir \
--import-alias "@/*"Elite Configuration ():
next.config.tstypescript
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
experimental: {
ppr: true, // Enable Partial Pre-rendering
dynamicIO: true, // New IO optimization for Next.js 16
reactCompiler: true, // Stable React Compiler support
},
logging: {
fetches: {
fullUrl: true,
},
},
};
export default nextConfig;初始化一个精英级项目:
bash
npx create-next-app@latest my-elite-app \
--typescript \
--tailwind \
--eslint \
--app \
--src-dir \
--import-alias "@/*"精英级配置():
next.config.tstypescript
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
experimental: {
ppr: true, // Enable Partial Pre-rendering
dynamicIO: true, // New IO optimization for Next.js 16
reactCompiler: true, // Stable React Compiler support
},
logging: {
fetches: {
fullUrl: true,
},
},
};
export default nextConfig;The Proxy Revolution (proxy.ts
)
proxy.ts代理革命(proxy.ts
)
proxy.tsIn Next.js 16, is legacy. All global network logic must reside in . This stabilizes the runtime and provides a clean gate for all requests.
middleware.tsproxy.tsStandard Elite Proxy ():
src/app/proxy.tstypescript
import { nextProxy } from 'next/server';
export default nextProxy(async (request) => {
const url = request.nextUrl;
// Global Routing Logic
if (url.pathname.startsWith('/api/v1')) {
// Standardize API versioning at the proxy level
}
// Security Headers & Request Decoration
request.headers.set('X-Elite-Engine', '16.1.1');
const response = await fetch(request);
// Performance Monitoring
response.headers.set('Server-Timing', 'elite;dur=20');
return response;
});For deep-dives into A/B testing and advanced security, see proxy-deep-dive.md.
在Next.js 16中,已成为遗留方案。所有全局网络逻辑必须放在中,这能稳定运行时,并为所有请求提供一个清晰的入口。
middleware.tsproxy.ts标准精英级代理():
src/app/proxy.tstypescript
import { nextProxy } from 'next/server';
export default nextProxy(async (request) => {
const url = request.nextUrl;
// Global Routing Logic
if (url.pathname.startsWith('/api/v1')) {
// Standardize API versioning at the proxy level
}
// Security Headers & Request Decoration
request.headers.set('X-Elite-Engine', '16.1.1');
const response = await fetch(request);
// Performance Monitoring
response.headers.set('Server-Timing', 'elite;dur=20');
return response;
});如需深入了解A/B测试与进阶安全内容,请查看proxy-deep-dive.md。
Unified Caching (use cache
)
use cache统一缓存(use cache
)
use cacheNext.js 16 introduces the directive, replacing the complexity of with explicit, function-level caching.
use cacherevalidatePathCached Data Service ():
src/services/data.tstypescript
import { cacheLife, cacheTag } from 'next/cache';
export async function getGlobalMetrics() {
'use cache';
cacheLife(60); // Cache for 60 seconds
cacheTag('metrics');
const data = await fetch('https://api.internal/metrics').then(r => r.json());
return data;
}Invalidation Patterns:
- : Immediate purge.
revalidateTag('metrics') - : Recommended. Marks as stale and revalidates in background (SWR).
updateTag('metrics')
For complex caching strategies, see unified-caching.md.
Next.js 16引入了指令,以显式的函数级缓存替代复杂的。
use cacherevalidatePath缓存数据服务():
src/services/data.tstypescript
import { cacheLife, cacheTag } from 'next/cache';
export async function getGlobalMetrics() {
'use cache';
cacheLife(60); // Cache for 60 seconds
cacheTag('metrics');
const data = await fetch('https://api.internal/metrics').then(r => r.json());
return data;
}失效模式:
- :立即清除缓存。
revalidateTag('metrics') - :推荐方案。标记为过期并在后台重新验证(SWR模式)。
updateTag('metrics')
如需了解复杂缓存策略,请查看unified-caching.md。
React 19.2 Patterns
React 19.2实践模式
Leverage the stability of React 19.2 within Next.js 16 to eliminate boilerplate.
在Next.js 16中利用React 19.2的稳定性,消除冗余代码。
1. useActionState
for Forms
useActionState1. 表单使用useActionState
useActionStateEliminate manual loading and error states in Client Components.
tsx
'use client';
import { useActionState } from 'react';
import { signUpAction } from '@/actions/auth';
export function SignUpForm() {
const [state, action, isPending] = useActionState(signUpAction, null);
return (
<form action={action}>
<input name="email" type="email" required />
{state?.errors?.email && <p className="text-red-500">{state.errors.email}</p>}
<button disabled={isPending}>
{isPending ? 'Processing...' : 'Sign Up'}
</button>
</form>
);
}消除客户端组件中手动处理加载与错误状态的代码。
tsx
'use client';
import { useActionState } from 'react';
import { signUpAction } from '@/actions/auth';
export function SignUpForm() {
const [state, action, isPending] = useActionState(signUpAction, null);
return (
<form action={action}>
<input name="email" type="email" required />
{state?.errors?.email && <p className="text-red-500">{state.errors.email}</p>}
<button disabled={isPending}>
{isPending ? 'Processing...' : 'Sign Up'}
</button>
</form>
);
}2. The <Activity />
Component
<Activity />2. <Activity />
组件
<Activity />Use for pre-rendering background tabs or hidden UI without performance cost.
tsx
import { Activity } from 'react';
export function TabSystem({ activeTab }) {
return (
<>
<Activity mode={activeTab === 'home' ? 'visible' : 'hidden'}>
<HomeTab />
</Activity>
<Activity mode={activeTab === 'settings' ? 'visible' : 'hidden'}>
<SettingsTab />
</Activity>
</>
);
}用于预渲染后台标签页或隐藏UI,且无性能损耗。
tsx
import { Activity } from 'react';
export function TabSystem({ activeTab }) {
return (
<>
<Activity mode={activeTab === 'home' ? 'visible' : 'hidden'}>
<HomeTab />
</Activity>
<Activity mode={activeTab === 'settings' ? 'visible' : 'hidden'}>
<SettingsTab />
</Activity>
</>
);
}Data Fetching & Mutations
数据获取与变更
Server-First Approach (RSC)
服务器优先方案(RSC)
80% of your data should be fetched in Server Components.
tsx
// app/dashboard/page.tsx
import { getGlobalMetrics } from '@/services/data';
export default async function Page() {
const metrics = await getGlobalMetrics(); // Direct, cached call
return (
<div>
<h1>Dashboard</h1>
<pre>{JSON.stringify(metrics, null, 2)}</pre>
</div>
);
}80%的数据应在服务器组件中获取。
tsx
// app/dashboard/page.tsx
import { getGlobalMetrics } from '@/services/data';
export default async function Page() {
const metrics = await getGlobalMetrics(); // Direct, cached call
return (
<div>
<h1>Dashboard</h1>
<pre>{JSON.stringify(metrics, null, 2)}</pre>
</div>
);
}Server Actions (Mutations)
服务器操作(变更)
Mandatory for all POST/PATCH/DELETE operations.
typescript
// actions/auth.ts
'use server';
import { updateTag } from 'next/cache';
export async function signUpAction(prevState: any, formData: FormData) {
const email = formData.get('email');
try {
await db.user.create({ data: { email } });
updateTag('users'); // Background revalidation
return { success: true };
} catch (e) {
return { errors: { email: 'Invalid email' } };
}
}所有POST/PATCH/DELETE操作必须使用此方案。
typescript
// actions/auth.ts
'use server';
import { updateTag } from 'next/cache';
export async function signUpAction(prevState: any, formData: FormData) {
const email = formData.get('email');
try {
await db.user.create({ data: { email } });
updateTag('users'); // Background revalidation
return { success: true };
} catch (e) {
return { errors: { email: 'Invalid email' } };
}
}Component Design & Single Responsibility
组件设计与单一职责
- 300-Line Rule: Keep component files under 300 lines. If a component exceeds this, extract sub-components or move logic to or
hooks/.services/ - Hydration Guard: Always protect components that depend on browser-only state.
tsx
'use client';
import { useState, useEffect } from 'react';
export function SafeClientComponent({ children }) {
const [mounted, setMounted] = useState(false);
useEffect(() => setMounted(true), []);
if (!mounted) return <div className="animate-pulse" />; // Placeholder
return <>{children}</>;
}- 300行规则:组件文件代码量控制在300行以内。若超过此限制,需提取子组件或将逻辑迁移至或
hooks/目录。services/ - Hydration防护:始终保护依赖浏览器独有状态的组件。
tsx
'use client';
import { useState, useEffect } from 'react';
export function SafeClientComponent({ children }) {
const [mounted, setMounted] = useState(false);
useEffect(() => setMounted(true), []);
if (!mounted) return <div className="animate-pulse" />; // Placeholder
return <>{children}</>;
}The 'Do Not' List (Anti-Patterns)
“请勿”清单(反模式)
- DO NOT use : Use
middleware.ts.proxy.tsis considered legacy and less performant in Next.js 16.middleware.ts - DO NOT use for simple UI updates: Use
revalidatePathwithin Server Actions for a better UX (Stale-While-Revalidate).updateTag - DO NOT access cookies in RSC without Suspense: Accessing or
cookies()makes a route dynamic. Wrap the dependent component inheaders()to keep the rest of the page static (PPR).<Suspense> - DO NOT use Barrel Files () for components: This kills tree-shaking and bloats the bundle. Import directly from the component file.
index.ts - DO NOT hardcode API URLs: Use environment variables and the layer to manage environments.
proxy.ts
- 请勿使用:请使用
middleware.ts。在Next.js 16中,proxy.ts被视为遗留方案,性能更差。middleware.ts - 请勿为简单UI更新使用:在服务器操作中使用
revalidatePath以获得更好的用户体验(Stale-While-Revalidate模式)。updateTag - 请勿在RSC中不使用Suspense就访问Cookie:访问或
cookies()会使路由变为动态路由。将依赖组件包裹在headers()中,以保持页面其余部分为静态(PPR)。<Suspense> - 请勿为组件使用桶文件():这会破坏摇树优化(tree-shaking)并增加包体积。直接从组件文件导入。
index.ts - 请勿硬编码API地址:使用环境变量与层管理不同环境。
proxy.ts
Advanced References
进阶参考
- Proxy Deep Dive — Advanced routing and security.
- Unified Caching — Master the directive.
use cache - React Expert — For deep performance optimizations.
- Supabase Expert — For backend and auth integration.
Optimized for Next.js 16.1.1 and React 19.2. Updated: January 22, 2026 - 14:36
- Proxy深度解析 — 进阶路由与安全内容。
- 统一缓存 — 精通指令。
use cache - React专家 — 深入性能优化内容。
- Supabase专家 — 后端与认证集成内容。
针对Next.js 16.1.1与React 19.2优化。更新时间:2026年1月22日 14:36