import { ApolloClient, InMemoryCache, createHttpLink } from '@apollo/client'; import { setContext } from '@apollo/client/link/context'; // 创建HTTP链接 const httpLink = createHttpLink({ uri: process.env.NEXT_PUBLIC_GRAPHQL_BACKEND_URL || 'http://localhost:4000/graphql', }); // 认证链接 const authLink = setContext((_, { headers }) => { // 从localStorage或cookie获取token const token = typeof window !== 'undefined' ? localStorage.getItem('token') : null; return { headers: { ...headers, authorization: token ? `Bearer ${token}` : "", } } }); // 创建Apollo客户端 export const gqlClient = new ApolloClient({ link: authLink.concat(httpLink), cache: new InMemoryCache(), ssrMode: typeof window === 'undefined', }); // 服务端专用的客户端(无认证) export const serverGqlClient = new ApolloClient({ link: httpLink, cache: new InMemoryCache(), ssrMode: true, });