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

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()获取请求头,属于动态服务器资源,导致预渲染失败。

解决步骤

  1. 强制动态渲染:在路由文件顶部添加dynamic指令,告知Next.js该路由必须使用动态服务器渲染,跳过静态预渲染:
export const dynamic = 'force-dynamic'; // 新增该行

import { getServerSession } from "next-auth";
// 其余代码保持不变
  1. 优化错误处理:原代码直接抛出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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 14:02:48