无法在Next.js 14中配置Apollo Client GraphQL,寻求帮助
Next.js 14 + Apollo Client 无法加载GraphQL数据的修复方案
问题根源
- App Router适配问题:直接使用
@apollo/client的ApolloProvider在Next.js 14 App Router中适配性不足,官方提供了专为App Router设计的包装组件 - ApolloClient配置冲突:同时设置了
uri和link属性,且HttpLink的目标地址配置错误 - 冗余配置:用
from()包裹单个HttpLink完全没必要
具体修复步骤
1. 修正Apollo Client配置(src/lib/client.js)
移除冲突的uri配置,直接将HttpLink指向你的Apollo Server地址:
import { ApolloClient, HttpLink, InMemoryCache } from "@apollo/client"; const httpLink = new HttpLink({ uri: "http://localhost:4000/", // 替换为你的Apollo Server实际地址 }); const client = new ApolloClient({ cache: new InMemoryCache(), link: httpLink, }); export default client;
2. 创建适配App Router的ApolloWrapper(src/lib/apollo-wrapper.js)
由于App Router中服务器组件无法直接使用客户端hooks,需要创建带"use client"指令的包装组件:
"use client"; import { ApolloProvider } from "@apollo/client"; import client from "./client"; export function ApolloWrapper({ children }) { return <ApolloProvider client={client}>{children}</ApolloProvider>; }
3. 在RootLayout中替换为ApolloWrapper(src/app/layout.js)
将原来的ApolloProvider替换为上面创建的Wrapper:
import { Inter } from "next/font/google"; import "./globals.css"; import { ApolloWrapper } from "../lib/apollo-wrapper"; const inter = Inter({ subsets: ["latin"] }); export const metadata = { title: "Create Next App", description: "Generated by create next app", }; export default function RootLayout({ children }) { return ( <html lang="en"> <body className={inter.className}> <ApolloWrapper>{children}</ApolloWrapper> </body> </html> ); }
4. 编写测试页面验证(src/app/page.js)
所有使用Apollo hooks的组件必须标记为客户端组件:
"use client"; import { useQuery, gql } from "@apollo/client"; // 替换为你的实际GraphQL查询 const GET_SAMPLE_DATA = gql` query GetSampleData { hello } `; export default function Home() { const { loading, error, data } = useQuery(GET_SAMPLE_DATA); if (loading) return <p>加载中...</p>; if (error) return <p>请求错误: {error.message}</p>; return <div>获取到的数据: {data?.hello}</div>; }
额外注意事项
- 所有调用
useQuery/useMutation等Apollo hooks的组件,必须添加"use client";指令 - 确认Apollo Server的CORS配置允许Next.js应用(默认localhost:3000)访问,若存在跨域问题,需在Apollo Server启动时配置
cors: { origin: "http://localhost:3000" } - 建议将
@apollo/client从RC版本(3.9.0-rc.1)换成稳定版(如3.8.0),避免潜在的兼容性问题
内容的提问来源于stack exchange,提问作者Kevin Smith
相关产品推荐
相关产品推荐

