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

Next.js 13中路由处理器获取的数据是否会被缓存?

Next.js 13路由处理器的数据缓存问题

Next.js 13中路由处理器里的fetch请求默认会被缓存,也就是说第一次调用路由处理器时会请求外部API,之后相同的请求会直接返回缓存的数据,不用重复调用外部API。

缓存行为的控制方式

  • 强制不缓存:如果希望每次请求都重新调用外部API,给fetch添加cache: 'no-store'配置:

    export async function GET() {
      const response = await fetch('https://api.example.com/users', {
        cache: 'no-store'
      });
      const users = await response.json();
    
      return new Response(JSON.stringify(users));
    }
    
  • 设置缓存有效期:如果想让数据在指定时间后自动更新,可以用next.revalidate配置缓存过期时间(单位:秒):

    export async function GET() {
      const response = await fetch('https://api.example.com/users', {
        next: { revalidate: 300 } // 5分钟后重新获取数据并更新缓存
      });
      const users = await response.json();
    
      return new Response(JSON.stringify(users));
    }
    

补充说明

你客户端调用路由处理器的fetch('/api/users')不会影响服务器端的缓存逻辑——服务器端的缓存由Next.js控制,而客户端的请求如果是浏览器发起的,浏览器可能会有自己的缓存策略,但这和服务器端路由处理器对外部API的缓存是两回事。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 15:09:53