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

如何获取Next.js缓存条目的时间戳并在Next.js 15页面展示缓存生成时间?

在Next.js 15中获取缓存生成时间戳并展示

Next.js 15并没有提供直接从@next/something这类模块获取缓存时间戳的API,你需要通过自定义逻辑在缓存数据/页面时注入时间信息,以下是几种可行方案:

方案1:结合unstable_cache实现带时间戳的缓存(适用于ISR或服务器组件缓存)

利用Next.js的unstable_cache(注意:该API为不稳定特性,生产环境使用需关注版本更新)包裹数据获取逻辑,同时记录缓存生成的时间戳:

// app/page.tsx
import { unstable_cache } from 'next/cache';

// 定义带缓存的函数,返回数据与生成时间戳
const getPageCacheInfo = unstable_cache(
  async () => {
    // 记录当前时间作为缓存生成时间
    const cacheTimestamp = new Date().toLocaleString();
    // 这里可以添加你的业务数据获取逻辑
    return { cacheTimestamp };
  },
  ['home-page-cache'], // 唯一缓存键,用于标识缓存条目
  { revalidate: 3600 } // 缓存有效期,单位为秒,到期自动重新生成
);

export default async function HomePage() {
  const { cacheTimestamp } = await getPageCacheInfo();
  return <p>页面缓存生成于:{cacheTimestamp}</p>;
}

方案2:静态页面构建时记录时间戳(适用于纯静态SSG页面)

如果你的页面是纯静态生成(无动态数据、无ISR),可以直接在组件顶层定义时间戳,该时间会在构建时固化到页面中:

// app/page.tsx
// 构建阶段执行,生成静态时间戳
const buildTimestamp = new Date().toLocaleString();

export default function HomePage() {
  return <p>页面静态构建于:{buildTimestamp}</p>;
}

方案3:手动管理缓存时间戳(灵活控制场景)

如果需要更灵活的缓存时间管理,可以将时间戳与业务数据一起存储,比如在数据获取时同时保存时间信息:

// app/page.tsx
import { cache } from 'next/cache';

async function fetchDataWithTimestamp() {
  // 检查是否有缓存
  const cachedData = cache.get('page-data');
  if (cachedData) {
    return cachedData;
  }
  // 无缓存时重新获取数据并记录时间
  const data = await fetch('https://api.example.com/data').then(res => res.json());
  const timestamp = new Date().toISOString();
  const cacheValue = { data, timestamp };
  // 手动设置缓存
  cache.set('page-data', cacheValue, { revalidate: 3600 });
  return cacheValue;
}

export default async function HomePage() {
  const { timestamp } = await fetchDataWithTimestamp();
  return <p>页面缓存生成于:{timestamp}</p>;
}

注意事项

  • unstable_cache属于实验性API,未来版本可能会有变更,使用前请确认官方文档
  • 所有方案均基于服务器组件执行,因为客户端组件无法直接访问服务器端缓存
  • ISR页面在重新验证(revalidate)时,时间戳会自动更新为新的生成时间

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 18:55:05