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

Next.js构建触发PrismaClientInitializationError:为何需访问数据库?

问题

执行npm run build构建Next.js应用时,原本期望动态查询数据的路由在构建阶段请求了数据库,由于构建环境未启动数据库,触发了PrismaClientInitializationError。原本以为动态渲染是默认行为,但Next.js却把这些页面判定为需要构建时静态渲染,想知道哪里配置出错了。

页面代码

export default async function Page() {
  const data = await prisma.my_data.findMany()
  return (
    <div>
        { /* 使用data渲染HTML元素 */ }
    </div>
  )
}

报错信息

67.05 Can't reach database server at `postgresdb`:`5432`
67.05
67.05 Please make sure your database server is running at `postgresdb`:`5432`.
67.05     at wn.handleRequestError (/app/.next/server/chunks/438.js:6947:32)
67.05     at wn.handleAndLogRequestError (/app/.next/server/chunks/438.js:6908:18)
67.05     at wn.request (/app/.next/server/chunks/438.js:6890:18)
67.05     at async l1 (/app/.next/server/chunks/438.js:7438:26)
67.05     at async getProductionsCrawlerStatus (/app/.next/server/chunks/605.js:27:12)
67.05     at async Page (/app/.next/server/app/(main)/partyfinder/status/page.js:555:25) {
67.05   clientVersion: '5.3.1',
67.05   errorCode: undefined
67.05 }
解决方案

Next.js 13+ 的 App Router 中,默认会对包含异步数据获取的页面进行静态渲染(Static Rendering)——也就是在构建阶段执行数据查询并生成静态HTML。如果你的页面需要在每次请求时动态获取数据,必须显式声明。

方法1:强制动态渲染

在页面文件顶部添加dynamic = "force-dynamic"指令,让数据查询在用户每次请求时执行,而非构建阶段:

export const dynamic = "force-dynamic";

export default async function Page() {
  const data = await prisma.my_data.findMany()
  return (
    <div>
        { /* 使用data渲染HTML元素 */ }
    </div>
  )
}

方法2:增量静态再生(可选)

如果希望兼顾静态页面的性能和数据新鲜度,可使用ISR(增量静态再生),通过revalidate参数设置页面重新生成的间隔:

export const revalidate = 60; // 每60秒重新生成一次页面

export default async function Page() {
  const data = await prisma.my_data.findMany()
  return (
    <div>
        { /* 使用data渲染HTML元素 */ }
    </div>
  )
}

注意:ISR仍会在构建阶段执行一次数据查询,如果构建环境无法访问数据库,还是会报错,这种场景优先选force-dynamic。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 06:00:13