You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js 14 App Router中Apollo Client封装及配置问题咨询

Next.js 14(App Router)集成Apollo Client 常见问题解答

一、Apollo Provider 应该封装在 layout.js 还是 page.js?

直接在根 app/layout.js 里用 Apollo Provider 包裹所有内容即可——App Router 的根 layout 是全局生效的,所有页面都会继承这个布局,这样你不用在每个 page.js 里重复封装,一次配置全项目可用。

具体实现代码:

在 app/layout.js 中导入 ApolloProvider 和你创建的 apolloClient:

import { ApolloProvider } from '@apollo/client';
import { apolloClient } from './util/apolloClient';

export default function RootLayout({ children }) {
  return (
    <html lang="zh-CN">
      <body>
        <ApolloProvider client={apolloClient}>
          {children}
        </ApolloProvider>
      </body>
    </html>
  );
}

之后所有页面组件都能直接使用 Apollo Client 的 hooks(比如 useQuery、useMutation),无需额外配置。

二、从 JSON 文件获取 GraphQL 配置

按以下步骤操作即可:

  1. 创建 GraphQL 配置 JSON 文件:在 app 目录下新建 config 文件夹,再创建 graphql.json 文件写入配置内容,比如:
{
  "endpoint": "https://your-apollo-server-url/graphql",
  "headers": {
    "authorization": "Bearer YOUR_TOKEN"
  }
}
  1. 在 apolloClient.ts 中导入并使用配置:Next.js 14 支持直接导入 JSON 文件,客户端或通用场景下可以这样写:
import { ApolloClient, InMemoryCache, createHttpLink } from '@apollo/client';
import { setContext } from '@apollo/client/link/context';
import graphqlConfig from '../config/graphql.json';

const httpLink = createHttpLink({
  uri: graphqlConfig.endpoint,
});

const authLink = setContext((_, { headers }) => {
  return {
    headers: {
      ...headers,
      ...graphqlConfig.headers,
    },
  };
});

export const apolloClient = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache(),
});

如果配置涉及敏感密钥,需要在服务器端读取,可改用 fs 模块读取(仅在服务器组件/API 路由中使用):

import { readFileSync } from 'fs';
import { join } from 'path';

const configPath = join(process.cwd(), 'app/config/graphql.json');
const graphqlConfig = JSON.parse(readFileSync(configPath, 'utf8'));

内容的提问来源于stack exchange,提问作者user17449555

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 00:22:15