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

Next.js API本地正常,Vercel部署后返回404求助

Next.js 14 API部署到Vercel后返回404(Prisma + MongoDB环境)

问题背景

本地开发时,基于Next.js 14的应用API(通过Prisma连接MongoDB)运行完全正常,但部署到Vercel后,访问/api/blog和/api/blog/[id]均返回404错误。已确认环境变量配置正确,且MongoDB Atlas已与Vercel集成,但问题仍未解决。

相关代码

app/api/blog/route.ts

import {db} from "@/lib/db";
import { NextResponse } from "next/server";

export async function GET(){
    try{
        const todos=await db.post.findMany({
            orderBy:{
                date:"desc",
            }
        });
        return NextResponse.json(todos,{status:200})
    }catch(error){
        console.log("[GET TODO]",error)
        return new NextResponse("Internal Server Error",{status:500})
    }
}

app/api/blog/[id]/route.ts

import {db} from "@/lib/db";
import { NextResponse } from "next/server";

export const GET = async (request:any,{params}:any)=>{
  try{
    const {id}=params;
    const post=await db.post.findUnique({
      where:{
        id
      }
    });
    if(!post){
      return NextResponse.json(
        {message:"Post not found",error: "Post not found"},
        {status:404}
        )
    }
    return NextResponse.json(post)
  }catch(err){
    return NextResponse.json({message:"GET Error",err},{status:500})
  }
}

package.json

{
  "name": "portfolio",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint",
    "postinstall": "prisma generate"
  },
  "dependencies": {
    "@material-tailwind/react": "^2.1.6",
    "@motionone/utils": "^10.16.3",
    "@prisma/client": "^5.7.1",
    "@radix-ui/react-dropdown-menu": "^2.0.6",
    "@radix-ui/react-slot": "^1.0.2",
    "@tsparticles/engine": "^3.3.0",
    "@tsparticles/react": "^3.0.0",
    "@tsparticles/slim": "^3.3.0",
    "@vercel/analytics": "^1.2.2",
    "class-variance-authority": "^0.7.0",
    "clsx": "^2.1.0",
    "dotenv": "^16.3.1",
    "framer-motion": "^10.18.0",
    "lucide-react": "^0.294.0",
    "mongodb": "^6.3.0",
    "next": "14.0.3",
    "next-themes": "^0.2.1",
    "react": "^18",
    "react-awesome-reveal": "^4.2.8",
    "react-dom": "^18",
    "react-hot-toast": "^2.4.1",
    "react-type-animation": "^3.2.0",
    "resend": "^3.2.0",
    "tailwind-merge": "^2.2.1",
    "tailwindcss-animate": "^1.0.7",
    "tailwindcss-filters": "^3.0.0",
    "typewriter-effect": "^2.21.0"
  },
  "devDependencies": {
    "@types/node": "^20",
    "@types/react": "^18",
    "@types/react-dom": "^18",
    "autoprefixer": "^10.0.1",
    "eslint": "^8",
    "eslint-config-next": "14.0.3",
    "postcss": "^8",
    "prisma": "^5.7.1",
    "tailwindcss": "^3.3.0",
    "typescript": "^5"
  }
}

排查与解决方案

1. 检查Vercel部署日志

  • 确认构建阶段是否执行了prisma generate:postinstall脚本在Vercel生产环境默认会执行,但如果出现权限或网络问题,可能导致Prisma客户端未生成,进而API无法初始化。
  • 搜索日志中的Prisma、DATABASE_URL、connection等关键词,定位数据库连接或初始化错误。

2. 验证环境变量与MongoDB配置

  • 核对Vercel生产环境的DATABASE_URL与本地是否完全一致,注意MongoDB Atlas连接字符串的用户名、密码是否正确,特殊字符是否转义。
  • 临时将MongoDB Atlas的IP白名单设置为0.0.0.0/0,测试是否是IP限制导致无法连接(测试后需恢复安全配置)。

3. 确认Prisma客户端初始化方式

确保@/lib/db采用单例模式初始化PrismaClient,避免生产环境重复创建连接:

import { PrismaClient } from '@prisma/client'

const prisma = globalThis.prisma || new PrismaClient({
  log: ['query', 'error'] // 可选:开启日志便于排查问题
})

if (process.env.NODE_ENV !== 'production') globalThis.prisma = prisma

export const db = prisma

4. 检查API路由结构与Next.js配置

  • 确认API路由文件路径无拼写错误:app/api/blog/route.ts和app/api/blog/[id]/route.ts的文件名、文件夹名严格符合Next.js 14 app router的要求,注意路径大小写敏感。
  • 检查next.config.js中是否有自定义重写或路由规则,导致API路径被拦截。

5. 直接测试API请求

用curl或Postman直接请求部署后的API,查看原始响应:

curl -v https://yasith.vercel.app/api/blog

若实际返回500错误而非404,说明问题出在数据库连接或Prisma初始化,而非路由不存在。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 13:29:59