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
middleware.ts
to
proxy.ts
. It provides production-ready patterns for modern full-stack development.
Next.js 16.1.1与React 19.2生态的资深专家。本技能聚焦于高性能的Proxy & Cache范式、Partial Pre-rendering (PPR),以及从
middleware.ts
proxy.ts
的强制迁移,为现代全栈开发提供可用于生产环境的实践模式。

Table 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.ts
):
typescript
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.ts
):
typescript
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

In Next.js 16,
middleware.ts
is legacy
. All global network logic must reside in
proxy.ts
. This stabilizes the runtime and provides a clean gate for all requests.
Standard Elite Proxy (
src/app/proxy.ts
):
typescript
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.ts
已成为遗留方案
。所有全局网络逻辑必须放在
proxy.ts
中,这能稳定运行时,并为所有请求提供一个清晰的入口。
标准精英级代理(
src/app/proxy.ts
):
typescript
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

Next.js 16 introduces the
use cache
directive, replacing the complexity of
revalidatePath
with explicit, function-level caching.
Cached Data Service (
src/services/data.ts
):
typescript
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:
  • revalidateTag('metrics')
    : Immediate purge.
  • updateTag('metrics')
    : Recommended. Marks as stale and revalidates in background (SWR).
For complex caching strategies, see unified-caching.md.

Next.js 16引入了
use cache
指令,以显式的函数级缓存替代复杂的
revalidatePath
缓存数据服务(
src/services/data.ts
):
typescript
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')
    :立即清除缓存。
  • updateTag('metrics')
    推荐方案。标记为过期并在后台重新验证(SWR模式)。
如需了解复杂缓存策略,请查看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

1. 表单使用
useActionState

Eliminate 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

2.
<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
    hooks/
    or
    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
    middleware.ts
    : Use
    proxy.ts
    .
    middleware.ts
    is considered legacy and less performant in Next.js 16.
  • DO NOT use
    revalidatePath
    for simple UI updates
    : Use
    updateTag
    within Server Actions for a better UX (Stale-While-Revalidate).
  • DO NOT access cookies in RSC without Suspense: Accessing
    cookies()
    or
    headers()
    makes a route dynamic. Wrap the dependent component in
    <Suspense>
    to keep the rest of the page static (PPR).
  • DO NOT use Barrel Files (
    index.ts
    ) for components
    : This kills tree-shaking and bloats the bundle. Import directly from the component file.
  • DO NOT hardcode API URLs: Use environment variables and the
    proxy.ts
    layer to manage environments.

  • 请勿使用
    middleware.ts
    :请使用
    proxy.ts
    。在Next.js 16中,
    middleware.ts
    被视为遗留方案,性能更差。
  • 请勿为简单UI更新使用
    revalidatePath
    :在服务器操作中使用
    updateTag
    以获得更好的用户体验(Stale-While-Revalidate模式)。
  • 请勿在RSC中不使用Suspense就访问Cookie:访问
    cookies()
    headers()
    会使路由变为动态路由。将依赖组件包裹在
    <Suspense>
    中,以保持页面其余部分为静态(PPR)。
  • 请勿为组件使用桶文件(
    index.ts
    :这会破坏摇树优化(tree-shaking)并增加包体积。直接从组件文件导入。
  • 请勿硬编码API地址:使用环境变量与
    proxy.ts
    层管理不同环境。

Advanced References

进阶参考

  • Proxy Deep Dive — Advanced routing and security.
  • Unified Caching — Master the
    use cache
    directive.
  • 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