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

Next.js 13应用路由:如何禁用Serverless函数缓存?

解决Next.js 13 App Router接口在Vercel生产环境被缓存的问题

在Vercel生产环境中,Next.js 13 App Router的GET路由默认会被静态缓存,导致你的随机整数接口返回固定值。可以通过以下几种方式禁用缓存:

方式一:设置响应缓存头

直接在返回的NextResponse中添加Cache-Control头,明确告知客户端和CDN不要缓存响应:

import { randomInt } from "crypto";
import { NextResponse } from "next/server";

export async function GET() {
  const data = { revenue: randomInt(100) };
  const response = NextResponse.json(data);
  // 禁用所有缓存
  response.headers.set('Cache-Control', 'no-store, max-age=0, must-revalidate');
  return response;
}

no-store会强制每次请求都重新获取资源,不会在任何地方存储缓存副本。

方式二:配置路由动态渲染规则

在你的route.ts文件中导出dynamic或revalidate配置,强制路由为动态渲染模式:

方案A:使用dynamic: 'force-dynamic'

import { randomInt } from "crypto";
import { NextResponse } from "next/server";

// 强制路由每次请求都执行服务器端逻辑,不缓存
export const dynamic = 'force-dynamic';

export async function GET() {
  return NextResponse.json({ revenue: randomInt(100) });
}

方案B:使用revalidate: 0

import { randomInt } from "crypto";
import { NextResponse } from "next/server";

// 设置缓存过期时间为0,等同于禁用缓存
export const revalidate = 0;

export async function GET() {
  return NextResponse.json({ revenue: randomInt(100) });
}

这两种配置效果一致,都会让Vercel每次请求都运行你的接口代码,返回新的随机整数。

方式三:控制fetch缓存(可选)

如果你的接口内部有fetch请求,还可以通过fetchCache配置禁用fetch的缓存,但对于当前场景,前面两种方式已经足够:

export const fetchCache = 'force-no-store';

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 06:42:45