从apollo-server-micro升级到Apollo Server 4的迁移求助(Next.js)
Apollo Server 4 迁移指南(Next.js Pages 路由无服务器架构)
1. 替换依赖包
先卸载旧版Apollo Server相关依赖,安装适配Next.js的新版包:
npm uninstall apollo-server-micro apollo-server-core npm install @apollo/server @as-integrations/next graphql
注意:确保
graphql版本≥16.6.0,否则可能出现兼容性问题
2. 重构 Apollo Server 配置文件(server.js)
新版Apollo Server调整了插件体系和配置选项,修改如下:
import { ApolloServer } from '@apollo/server'; import { ApolloServerPluginCSRFPrevention } from '@apollo/server/plugin/csrf-prevention'; import { ApolloServerPluginLandingPageDisabled } from '@apollo/server/plugin/disabled'; import schema from './schema'; import resolvers from './resolvers'; import { context } from './context'; const typeDefs = schema; const server = new ApolloServer({ typeDefs, resolvers, cache: 'bounded', // 保留原缓存配置 plugins: [ // 替换原顶层csrfPrevention配置为插件形式 ApolloServerPluginCSRFPrevention({ allowUnsafeRequests: false, }), // 保留禁用着陆页的配置 ApolloServerPluginLandingPageDisabled(), ], }); export default server;
3. 更新 API 路由文件(pages/api/index.js)
使用@as-integrations/next提供的适配工具替换原createHandler,简化启动逻辑:
import Cors from 'micro-cors'; import server from '../../apollo/config/server'; import { createNextHandler } from '@as-integrations/next'; const cors = Cors(); export const config = { api: { bodyParser: false, }, }; // 创建适配Next.js的Apollo请求处理函数 const apolloHandler = createNextHandler(server, { // 传递上下文逻辑,若原context需要req/res可在此注入 context: async ({ req, res }) => context({ req, res }), }); export default cors(async (req, res) => { if (req.method === 'OPTIONS') { res.end(); return; } await apolloHandler(req, res); });
关键注意事项
- 上下文适配:若你的
context原本是静态对象,需改为函数形式(接收req/res参数并返回上下文对象) - 移除手动启动:新版无需提前调用
server.start(),createNextHandler会自动处理服务器初始化 - CORS配置:保留原
micro-cors配置即可,若需要更精细控制可在createNextHandler中调整
内容的提问来源于stack exchange,提问作者Orozcorp
相关产品推荐
相关产品推荐

