如何在 Next.js 中使用 Apollo Client 或 URQL 与 Vercel GraphQL API 交互?

解读

面试官问的不是“能不能用”,而是“怎么用、用得好”。国内一线团队普遍把 Vercel 当“前端托管 + Edge Function”双引擎,GraphQL 端点往往放在 /api/graphql 或独立微服务。考察点集中在:

  1. 客户端选型:Apollo 生态成熟、调试友好;URQL 包体小、可摇树,对首屏敏感的业务更友好。
  2. 渲染模式:Next.js 有 SSG、SSR、ISR、CSR 四种,国内 SEO 与秒开率并重,必须让数据请求发生在“正确的时间、正确的地点”。
  3. 边缘运行时:Vercel Edge Function 只支持“Web 标准 API”,Node 版 Apollo Server 无法直接运行,需要知道如何降级或换用 Yoga、Mercurius 等边缘兼容方案。
  4. 性能与缓存:国内网络多跳,边缘缓存 TTL、APQ(自动持久化查询)、Server–side cache-control 都要落地。
  5. 安全:内网 BFF 场景下,Edge Function 到后端服务需走 mTLS 或内网鉴权,不能直接把 Authorization 透传。

知识点

  • Next.js 数据获取三阶段:getStaticProps / getServerSideProps / 客户端 useEffect。
  • Apollo Client 3 的 SchemaLink(纯同构)、HttpLink(网络)、SSRMultipartLink(流式)各自适用场景。
  • URQL 的 ssrExchange 与 next-urql 包,如何把脱水数据序列化到 __URQL_DATA__。
  • Vercel Edge Runtime 限制:无 Node fs、child_process,node-fetch 不可用,只能用原生 fetch。
  • 国内 CDN 节点回源策略:Vercel 在中国内地无 ICP 节点,需额外接入阿里云全站加速或腾讯 ECDN,缓存键要剔除 set-cookie。
  • 代码拆分:GraphQL 查询文件按页面 import(),配合 @graphql-codegen/gql-tag-operations-preset 把 2000+ 字段的 schema 摇树到只传 3 KB。
  • 错误边界:Next.js 自定义 _error.tsx,把 GraphQL 网络错误码(GRAPHQL_VALIDATION_FAILED、UNAUTHENTICATED)映射到 400/401/500,方便国内监控平台(SLS、ARMS)统一告警。

答案

下面给出可直接落地的两段代码,分别对应“Apollo”与“URQL”两种主流选型,均满足“Edge Runtime 友好 + 国内秒开 + SEO”要求。

一、Apollo Client 方案

  1. 安装依赖
pnpm add @apollo/client graphql
  1. 创建 lib/apollo.ts
import { ApolloClient, InMemoryCache, HttpLink, from } from '@apollo/client';
import { onError } from '@apollo/client/link/error';
import { VERCEL_URL, NODE_ENV } from '@/constants/env';

const httpLink = new HttpLink({
  uri: `${VERCEL_URL}/api/graphql`,
  credentials: 'same-origin', // 同域自动带 cookie
  fetchOptions: { cache: 'force-cache' }, // 利用 Vercel Edge Cache
});

const errorLink = onError(({ graphQLErrors, networkError }) => {
  if (graphQLErrors)
    graphQLErrors.forEach(({ message, extensions }) => {
      console.error(`[GraphQL error]: ${message}, code: ${extensions?.code}`);
    });
  if (networkError) console.error(`[Network error]: ${networkError}`);
});

export const apolloClient = new ApolloClient({
  ssrMode: typeof window === 'undefined',
  link: from([errorLink, httpLink]),
  cache: new InMemoryCache({
    typePolicies: {
      Query: {
        fields: {
          posts: {
            keyArgs: ['category'],
            merge(existing = [], incoming) {
              return [...existing, ...incoming];
            },
          },
        },
      },
    },
  }),
  defaultOptions: {
    watchQuery: { fetchPolicy: 'cache-first', errorPolicy: 'all' },
    query: { fetchPolicy: 'cache-first', errorPolicy: 'all' },
  },
});
  1. 页面级 SSR 数据获取 pages/posts.tsx
import { apolloClient } from '@/lib/apollo';
import { gql } from '@apollo/client';
import { initializeApollo } from '@/lib/apollo';

const POSTS = gql`
  query GetPosts($category: String!) {
    posts(category: $category) {
      id
      title
      cover
    }
  }
`;

export async function getServerSideProps(context) {
  const client = initializeApollo(); // 每次请求新建实例,防止缓存污染
  const { category = 'tech' } = context.query;
  await client.query({ query: POSTS, variables: { category } });
  return {
    props: {
      initialApolloState: client.cache.extract(),
      category,
    },
  };
}

export default function Posts({ initialApolloState, category }) {
  const { data } = useQuery(POSTS, {
    variables: { category },
    skip: !category,
  });
  return (
    <ul>
      {data?.posts.map(p => (
        <li key={p.id}>{p.title}</li>
      ))}
    </ul>
  );
}
  1. 边缘函数 /api/graphql.ts
import { createYoga } from 'graphql-yoga';
import { schema } from '@/graphql/schema';

export default createYoga({
  schema,
  graphqlEndpoint: '/api/graphql',
  fetchAPI: { Response }, // 显式指定边缘环境
});

二、URQL 方案

  1. 安装
pnpm add urql @urql/exchange-graphcache graphql
  1. 创建 lib/urql.ts
import { createClient, cacheExchange, fetchExchange, ssrExchange } from 'urql';
import { VERCEL_URL } from '@/constants/env';

const isServer = typeof window === 'undefined';
const ssrCache = ssrExchange({ isClient: !isServer });

const client = createClient({
  url: `${VERCEL_URL}/api/graphql`,
  exchanges: [cacheExchange, ssrCache, fetchExchange],
  fetchOptions: () => ({
    headers: isServer ? { 'x-forwarded-proto': 'https' } : {},
  }),
});

export { client, ssrCache };
  1. 页面级 SSR pages/products.tsx
import { client, ssrCache } from '@/lib/urql';
import { queryProducts } from '@/queries/products.graphql';

export async function getServerSideProps() {
  const { data } = await client.query(queryProducts, {}).toPromise();
  return {
    props: {
      urqlState: ssrCache.extractData(),
      products: data.products,
    },
  };
}

export default function Products({ products }) {
  return (
    <ul>
      {products.map(p => (
        <li key={p.id}>{p.name}</li>
      ))}
    </ul>
  );
}
  1. 客户端注水 _app.tsx
import { Provider } from 'urql';
import { client, ssrCache } from '@/lib/urql';

function MyApp({ Component, pageProps }) {
  if (pageProps.urqlState) {
    ssrCache.restoreData(pageProps.urqlState);
  }
  return (
    <Provider value={client}>
      <Component {...pageProps} />
    </Provider>
  );
}

拓展思考

  1. 国内合规:若 GraphQL 网关部署在阿里云函数计算,需把 Vercel Edge Function 当作“轻量 BFF”,只负责拼装参数与缓存,不走外网,避免跨境回源。
  2. persisted query:把 5 KB 的查询语句压缩成 64 位哈希,Edge Function 先查 Redis,未命中再回源,降低 30% 带宽费用。
  3. 微前端:在 Monorepo 里把商品、营销、用户三个子域拆成独立 Next.js 应用,共用同一份 GraphQL Schema,通过 Module Federation 在运行时拼接,Vercel 的“Zero Config”依然生效。
  4. 灰度发布:利用 Vercel 的 preview URL,把 GraphQL 变量 x-vercel-env=preview 传给网关,按用户白名单返回新 schema,实现“前端无感灰度”。
  5. 监控闭环:把 GraphQL 错误码统一打到 SLS,结合 traceparent 做全链路追踪,国内 4 G 弱网场景下可快速定位“解析超时”或 N + 1 问题。