如何在 `async` Server Component 中调用 Mutation 并返回重定向?

解读

国内主流技术栈(Next.js 13 App Router、Remix、Nuxt 3)都支持“Server Component”概念:组件默认在服务端渲染,前端只拿到序列化后的 HTML/RSC 流。
Server Component 里不能出现 useMutation 这类客户端 Hook,也不能直接 router.push,因为服务端没有浏览器 History。
面试官真正想确认的是:

  1. 你分得清“服务端写数据”与“客户端写数据”的边界;
  2. 你知道在服务端触发 Mutation 后,如何把“写成功”信号带回前端并触发重定向;
  3. 你熟悉 Apollo Client 3.8+ 的“服务端链路”与 Next.js 官方推荐模式(@apollo/experimental-nextjs-app-support)。

一句话:把 Mutation 当成一次普通的 GraphQL 请求在服务端发掉,然后用框架级重定向 API(redirect() 或 Response.redirect)把浏览器打到目标地址。

知识点

  1. Server Component 生命周期:

    • 只在服务端跑,无 Hooks、无浏览器 API;
    • 可以 async,可以 fetch 或 apolloClient.mutate();
    • 必须返回可被序列化的 React 元素或抛 redirect()。
  2. Apollo Client 在服务端的使用姿势:

    • 每请求新建一个 ApolloClient 实例,禁用缓存(cache: new InMemoryCache() 即可),避免跨请求污染;
    • 用 SchemaLink(同进程直连)或 HttpLink(内网走 127.0.0.1)发 Mutation;
    • 出错时抛 new Error() 或返回 { error: true } 让前端兜底。
  3. Next.js App Router 重定向约定:

    • 抛 redirect('/target')(来自 next/navigation)会立即终止渲染并返回 307/303;
    • 不能 try/catch 住 redirect,否则流会断;
    • 如需条件跳转,在 Mutation 成功后再抛。
  4. 数据与 UI 同步策略:

    • 服务端写完后前端第一次渲染就是新数据,无需额外 refetchQueries;
    • 若页面同时需要“写后读”,可在同一 Server Component 里顺序发 Query。
  5. 安全与性能:

    • 服务端 Mutation 自带 Cookie,无需手动带 headers;
    • 大并发场景给 ApolloClient 加 requestDeduplication: false 防止 Node 层内存堆积。

答案

以下示例基于 Next.js 13 App Router + @apollo/experimental-nextjs-app-support,演示“点击表单 → Server Component 执行 Mutation → 写成功后重定向”的完整链路。

  1. 创建单例客户端(lib/apollo-server.ts)
import { ApolloClient, InMemoryCache, HttpLink } from '@apollo/client';
import { registerApolloClient } from '@apollo/experimental-nextjs-app-support/rsc';

export const { getClient } = registerApolloClient(() => {
  return new ApolloClient({
    cache: new InMemoryCache(),
    link: new HttpLink({
      uri: `${process.env.GRAPHQL_ENDPOINT}`, // 内网地址,如 http://graphql-svc.default.svc.cluster.local:4000/graphql
      headers: {
        // 如果服务端需要鉴权,把 Cookie 带过去
        cookie: require('next/headers').cookies().toString(),
      },
    }),
  });
});
  1. Server Component 页面(app/item/create/page.tsx)
import { getClient } from '@/lib/apollo-server';
import { redirect } from 'next/navigation';
import { CREATE_ITEM } from '@/graphql/mutations';

export default async function CreateItemPage({
  searchParams,
}: {
  searchParams: { name?: string };
}) {
  // 1. 服务端直接读表单参数(实际项目用 Server Action 或 POST + formData)
  if (!searchParams.name) {
    return <div>缺少 name 参数</div>;
  }

  // 2. 执行 Mutation
  const { data, errors } = await getClient().mutate({
    mutation: CREATE_ITEM,
    variables: { name: searchParams.name },
  });

  // 3. 失败场景
  if (errors?.length) {
    // 返回错误 UI,或抛给 error.tsx 边界
    return <div>创建失败:{errors[0].message}</div>;
  }

  // 4. 成功 → 重定向
  redirect(`/item/${data.createItem.id}`); // 抛 redirect 会立即终止渲染
}
  1. 前端触发方式(最简 GET 跳转)
'use client';
export function CreateButton() {
  const handleClick = () => {
    // 把表单数据带在 query 里,实际项目用 Server Action 或 POST
    const name = prompt('名称');
    if (name) location.href = `/item/create?name=${encodeURIComponent(name)}`;
  };
  return <button onClick={handleClick}>新建</button>;
}
  1. 如果框架是 Remix
export async function loader({ request }: LoaderArgs) {
  const url = new URL(request.url);
  const name = url.searchParams.get('name');
  if (!name) return json({ ok: false });

  const apollo = createApolloClient(); // 每请求新建
  const { data } = await apollo.mutate({ mutation: CREATE_ITEM, variables: { name } });
  return redirect(`/item/${data.createItem.id}`);
}

核心口诀:
“服务端 mutate → 拿到结果 → 抛 redirect → 浏览器 307 → 新页面 SSR 数据即最新”。

拓展思考

  1. Server Action 场景(Next.js 14)
    把 Mutation 放进 'use server' 的异步函数,前端可直接 await createItem(name),成功后在服务端 redirect();失败抛 new Error() 由 error.tsx 捕获。
    优点:POST 更安全、参数更大;缺点:需要 React Canary。

  2. 事务性重定向
    如果 Mutation 后还需再 Query 一次确认,可把“写+读”包在同一个 Server Component 里顺序执行,依旧一次性返回 HTML,前端无闪烁。

  3. 多环境隔离
    国内常见“一套代码 + 多套容器”:

    • 开发环境用 SchemaLink 直连本地 graphql-js 实例,秒级热更新;
    • 线上走 HttpLink 内网 K8s Service,配合 keepAlive: false 防止 Pod 漂移挂连接。
  4. 灰度与观测
    在 ApolloClient 的 errorLink 里把 graphQLErrors 打到阿里云 SLS,配合 traceparent 做全链路追踪;重定向失败率升高时及时回滚上游接口。

  5. 客户端兜底
    极端情况下用户禁用了自动重定向,可在 Server Component 返回 <meta http-equiv="refresh" content="0;URL=/item/${id}" /> 做双保险。