Next.js 14构建报错:预渲染/api/user页面触发动态服务器使用错误
Next.js 14 app目录API路由动态服务器使用错误排查
错误信息
[Error]: Dynamic server usage: Page couldn't be rendered statically because it used `headers`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error at l (/Users/joh/Documents/dev/waletoo/.next/server/chunks/185.js:30:30275) at u (/Users/joh/Documents/dev/waletoo/.next/server/chunks/185.js:30:26794) at s (/Users/joh/Documents/dev/waletoo/.next/server/chunks/185.js:30:20357) at p (/Users/joh/Documents/dev/waletoo/.next/server/app/api/user/route.js:1:1271) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) at async /Users/joh/Documents/dev/waletoo/node_modules/next/dist/compiled/next-server/app-route.runtime.prod.js:6:41304 { digest: 'DYNAMIC_SERVER_USAGE' } Error occurred prerendering page "/api/user". Read more: https://nextjs.org/docs/messages/prerender-error Error: Internal Server Error at p (/Users/joh/Documents/dev/waletoo/.next/server/app/api/user/route.js:1:1442)
路由代码
import { getServerSession } from "next-auth"; import connectDB from "@/src/mongoDB/connect"; import UserModel from "@/src/mongoDB/userSchema"; import { authOptions } from "@/src/utils/authOptions"; export async function GET() { await connectDB(); try { const session = await getServerSession(authOptions); if (!session?.user?.email) throw new Error("Unauthorized"); const userEmail = session.user.email; const userInformations = await UserModel.find({ email: userEmail }); return new Response(JSON.stringify(userInformations)); } catch (error) { console.error(error); throw new Error("Internal Server Error"); } }
问题分析与解决方法
核心问题
你的API路由被Next.js默认触发静态预渲染,但getServerSession内部会调用headers()获取请求头,属于动态服务器资源,导致预渲染失败。
解决步骤
- 强制动态渲染:在路由文件顶部添加
dynamic指令,告知Next.js该路由必须使用动态服务器渲染,跳过静态预渲染:
export const dynamic = 'force-dynamic'; // 新增该行 import { getServerSession } from "next-auth"; // 其余代码保持不变
- 优化错误处理:原代码直接抛出
Internal Server Error会覆盖原始错误信息,建议返回带对应HTTP状态码的响应,方便前端判断:
catch (error) { console.error(error); const statusCode = error.message === "Unauthorized" ? 401 : 500; return new Response(JSON.stringify({ error: error.message }), { status: statusCode }); }
内容的提问来源于stack exchange,提问作者Johan
相关产品推荐
相关产品推荐

