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

NextJs/Apollo/GraphQL中Context函数无法执行问题排查

Next.js中Apollo Server Context函数未触发的排查方案

1. 检查版本兼容性

如果最近升级了Apollo Server或@as-integrations/next包,可能出现版本不匹配导致的逻辑变化。可以回退到之前能正常运行的版本验证,确认是否是版本更新带来的适配问题。

2. 核对Context函数的写法

不同版本的Apollo Server和startServerAndCreateNextHandler对Context函数的参数要求可能不同,确保写法符合当前版本规范:

  • 实例化ApolloServer时传context:
    const server = new ApolloServer({
      typeDefs,
      resolvers,
      context: async ({ req, res }) => {
        console.log('Context触发');
        return { req, res };
      },
    });
    
  • 在startServerAndCreateNextHandler中配置context:
    export default startServerAndCreateNextHandler(server, {
      context: async (req, res) => {
        console.log('Handler Context触发');
        return { req, res };
      },
    });
    
    注意参数结构,部分版本是接收{ req, res }对象,部分是直接传入req和res两个参数。

3. 排查Next.js API路由的额外逻辑

检查你的API路由文件(如pages/api/graphql.js或app/api/graphql/route.js):

  • 是否有提前返回响应的中间件,跳过了Apollo Server的处理流程?
  • 是否有自定义的req/res修改逻辑,破坏了上下文传递?

4. 验证Resolver中的Context可用性

在Resolver里打印Context对象,确认是否能拿到值:

const resolvers = {
  Query: {
    test: (_, __, context) => {
      console.log('Resolver中的Context:', context);
      return 'test';
    },
  },
};

如果Resolver能拿到Context,说明Context函数实际已执行,只是日志没输出到你查看的控制台(注意区分Next.js客户端和服务器端控制台)。

5. 临时关闭缓存机制

若开启了自动持久化查询或其他缓存,缓存命中时可能跳过Context执行。可以临时关闭验证:

const server = new ApolloServer({
  typeDefs,
  resolvers,
  context: async ({ req, res }) => {
    console.log('Context触发');
    return { req, res };
  },
  persistedQueries: false,
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 16:42:34