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

Next.js生产环境无法获取MongoDB最新数据的问题求助

静态构建后无法同步MongoDB最新数据的问题

我正在搭建一个小型电商网站,通过MongoDB获取数据展示给用户。现在遇到的问题是:执行npm run build后页面被静态化,数据库更新后前端无法获取最新数据;本地开发环境(npm run dev)运行正常,但生产环境出现该问题。期望每次初始加载或刷新页面都能获取当前最新数据。


src/app/page.tsx 代码

// src/app/page.tsx

import { ProductData } from "@/utils/interface";
import HomeSlider from "@/components/HomeSlider";
import CollectionHighlights from "@/components/CollectionHighlights";
import TopProducts from "@/components/TopProducts";

// fetch function to get data from the API
const fetchProducts = async (): Promise<{ [key: string]: ProductData }> => {
  const res = await fetch("http://localhost:3000/api/products", {
    next: { revalidate: 60 }, 
  });
  if (!res.ok) {
    throw new Error("Failed to fetch products");
  }
  return res.json();
};

// Home component to serve the data to TopProduct component
const Home = async () => {
  try {
    const data = await fetchProducts();
    const products = Object.values(data);

    return (
      <main className="">
        <section className="px-3">
          <HomeSlider />
        </section>
        <section className="px-3 mt-10">
          <h1 className="text-center text-3xl sm:text-4xl font-extrabold text-slate-900 tracking-tight pb-5">
            Collections
          </h1>
          <CollectionHighlights />
        </section>
        <section className="px-3 mt-10">
          <h1 className="text-center text-3xl sm:text-4xl font-extrabold text-slate-900 tracking-tight pb-5">
            Top Products
          </h1>
          <TopProducts products={products} />
        </section>
      </main>
    );
  } catch (error) {
    console.error("Error fetching products:", error);
    return (
      <main className="">
        <section className="px-3">
          <HomeSlider />
        </section>
        <section className="px-3 mt-10">
          <h1 className="text-center text-3xl sm:text-4xl font-extrabold text-slate-900 tracking-tight pb-5">
            Collections
          </h1>
          <CollectionHighlights />
        </section>
        <section className="px-3 mt-10">
          <h1 className="text-center text-3xl sm:text-4xl font-extrabold text-slate-900 tracking-tight pb-5">
            Top Products
          </h1>
          <TopProducts products={[]} />{" "}
          {/* Provide empty array in case of error */}
        </section>
      </main>
    );
  }
};

export default Home;

src/app/api/route.ts 代码

// src/app/api/route.ts

import { connect } from "@/dbConfig/dbConfig";
import { Product } from "@/modal/products";
import { NextRequest, NextResponse } from "next/server";

connect();

export async function GET(req: NextRequest) {
  try {
    const products = await Product.find().exec();
    return NextResponse.json(products, {});
  } catch (error) {
    return NextResponse.json(
      { error: "Error occurred while fetching products" },
      { status: 500 }
    );
  }
}

npm run build 日志

$ npm run build

> rapido@0.1.0 build
> next build        

  ▲ Next.js 14.2.5
  - Environments: .env

   Creating an optimized production build ...

🌼   daisyUI 4.12.10
├─ ✔︎ 2 themes added            
╰─ ★ Star daisyUI on GitHub     

 ✓ Compiled successfully

info  - Need to disable some ESLint rules? Learn more here: https://nextjs.org/docs/basic-features/eslint#disabling-rules
 ✓ Linting and checking validity of types    
   Collecting page data  ..mongodb+srv://userAdmin:userPassword@userAdmin.xlllghj.mongodb.net/?retryWrites=true&w=majority&appName=eCommerceshop
 ✓ Collecting page data
   Generating static pages (0/7)  [=   ]MongoDB conected successfuly
   Generating static pages (5/7)  [ ===]mongodb+srv://userAdmin:userPassword@userAdmin.xlllghj.mongodb.net/?retryWrites=true&w=majority&appName=eCommerceshop
   Generating static pages (6/7)  [  ==]MongoDB conected successfuly
 ✓ Generating static pages (7/7)
 ✓ Collecting build traces    
 ✓ Finalizing page optimization

Route (app)                              Size     First Load JS
┌ ○ /                                    1.65 kB         117 kB
├ ○ /_not-found                          871 B          87.9 kB
├ ○ /api/products                        0 B                0 B
├ ○ /product                             137 B          87.2 kB
└ ƒ /product/[slug]                      395 B          87.4 kB
+ First Load JS shared by all            87 kB
  ├ chunks/23-9061b51442bf377f.js        31.5 kB
  ├ chunks/fd9d1056-81f448b567f73d85.js  53.6 kB
  └ other shared chunks (total)          1.86 kB


○  (Static)   prerendered as static content
ƒ  (Dynamic)  server-rendered on demand

解决方案

1. 强制首页动态渲染

从build日志可以看到首页/被标记为静态预渲染,导致构建后数据不会更新。在page.tsx顶部添加以下代码,强制页面每次请求都重新渲染:

export const dynamic = 'force-dynamic';

2. 取消fetch缓存或设置实时更新

当前fetch设置了60秒缓存,若要每次刷新都获取最新数据,修改fetch配置:

const res = await fetch("/api/products", {
  next: { revalidate: 0 }, // 禁用缓存,每次请求拉取最新数据
});

同时把硬编码的http://localhost:3000改为相对路径,适配生产环境。

3. 确保API路由动态化

在route.ts顶部添加动态指令,避免API被静态缓存:

export const dynamic = 'force-dynamic';

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 11:13:12