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 配置
按以下步骤操作即可:
- 创建 GraphQL 配置 JSON 文件:在
app目录下新建config文件夹,再创建graphql.json文件写入配置内容,比如:
{ "endpoint": "https://your-apollo-server-url/graphql", "headers": { "authorization": "Bearer YOUR_TOKEN" } }
- 在
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
相关产品推荐
相关产品推荐

