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

Vercel部署后Next.js获取最新指标接口缓存异常求助

解决Vercel部署后Next.js API接口缓存异常问题

问题分析

部署到Vercel后,获取最新温度数据的接口仅首次调用正常,后续返回缓存数据,响应头中x-vercel-cache: HIT表明Vercel边缘缓存命中了旧数据。而分页接口因为接收NextRequest参数,Next.js自动判定为动态路由,未触发缓存,所以正常工作。

解决方案

要实现无缓存效果,需从Next.js路由配置和响应头策略两个层面禁用缓存:

1. 修改API路由配置与响应头

在getLatest接口代码中添加动态路由强制配置,并显式设置禁止缓存的响应头:

import { NextResponse } from 'next/server';
import pg from '../../connection';

// 强制接口为动态执行模式,禁用静态缓存
export const dynamic = 'force-dynamic';

export async function GET() {
  try {
    const latestData = await pg('readings_temperature').select('*').orderBy('created_at', 'desc').first();

    if (!latestData) {
      return NextResponse.json({ status: 404, message: 'No data found.' }, { status: 404 });
    }

    return NextResponse.json(
      {
        status: 200,
        message: 'Successfully received the latest data.',
        data: latestData,
      },
      { 
        status: 200,
        headers: {
          // 禁止客户端、边缘节点缓存数据
          'Cache-Control': 'no-store, no-cache, must-revalidate, proxy-revalidate',
          'Pragma': 'no-cache',
          'Expires': '0'
        }
      }
    );
  } catch (err) {
    console.error('Error occurred:', err);
    const errorMessage = err instanceof Error ? err.message : 'Unknown error';
    return NextResponse.json(
      { status: 500, message: 'Failed to load data', error: errorMessage }, 
      { 
        status: 500,
        headers: {
          'Cache-Control': 'no-store, no-cache, must-revalidate, proxy-revalidate',
          'Pragma': 'no-cache',
          'Expires': '0'
        }
      }
    );
  }
}

2. 验证修改效果

重新部署到Vercel后,调用接口检查响应头:

  • x-vercel-cache应显示MISS(每次请求都回源拉取最新数据)
  • age字段值为0
  • Cache-Control与设置的no-store, no-cache, must-revalidate, proxy-revalidate一致

关键说明

  • Next.js App Router中,无参数的API路由默认会被静态优化缓存,dynamic: 'force-dynamic'可强制取消静态化,确保每次请求都执行接口逻辑。
  • no-store直接禁止任何缓存存储,proxy-revalidate告知Vercel边缘节点必须每次重新验证源数据,彻底避免边缘缓存旧数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 12:13:13