You need to enable JavaScript to run this app. 如何将Next.js中getServerSideProps内的查询逻辑提取到独立辅助文件?
优惠活动
大模型
产品
解决方案
定价
更多

如何将Next.js中getServerSideProps内的查询逻辑提取到独立辅助文件?

你出现缓存不更新的核心原因有两个:

  1. Cookie名称不一致
    你原有页面逻辑中读取的token是my_token,但抽离到withAuth.tsx后读取的是gc_token,这会导致请求头Authorization没有携带正确的用户凭证,接口返回无效/空数据,自然不会触发缓存更新。
  2. 没有返回withAuth的执行结果
    addApolloState方法会将服务端Apollo实例的缓存序列化后注入到返回的props中,你在getServerSideProps中仅调用了withAuth(context)但没有将它的返回值return出去,Next.js不会将序列化的缓存传递到客户端,自然看不到缓存更新。

修正后的代码

1. 调整withAuth.tsx逻辑

还可以额外支持合并页面自定义props,适配多页面的不同需求:

import { NextPageContext } from 'next';
import { addApolloState, initializeApollo } from 'lib/apolloClient';
import { MeDocument } from 'generated/types';
import nookies from 'nookies';

// 第二个参数支持传入自定义props生成逻辑
export const withAuth = async (
  context: NextPageContext,
  getCustomProps?: () => Promise<Record<string, any>>
) => {
  const client = initializeApollo();
  // 统一为正确的token名,和原有业务逻辑保持一致
  const { my_token } = nookies.get(context);

  await client.query({
    query: MeDocument,
    context: {
      headers: {
        authorization: my_token ? `Bearer ${my_token}` : '',
      },
    },
  });

  // 合并自定义props
  const customProps = getCustomProps ? await getCustomProps() : {};
  return addApolloState(client, { props: customProps });
};

2. 页面调用方式调整

export const getServerSideProps = async (
  context: NextPageContext
): Promise<any> => {
  // 直接返回withAuth的执行结果,第二个参数可传入页面需要的额外props
  return withAuth(context, async () => {
    // 示例:返回页面其他自定义服务端props
    return {
      // pageId: 123
    }
  });
};

修改后即可在多页面复用该逻辑,Apollo缓存也会正常同步到客户端。

内容的提问来源于stack exchange,提问作者J. Jackson

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 09:15:02