DevFlow

DevOverflow

Search
Menu
DevFlow

DevOverflow

Home menu icon

Home

Community menu icon

Community

Collections menu icon

Collections

Find Jobs menu icon

Find Jobs

Tags menu icon

Tags

Ask a question menu icon

Ask a question

    Profile

    Juan Cruz Cáceres

    upvote

    0

    downvote

    0

    star

    Next.js API routes: Prisma works in server components but "prisma is undefined" in API routes on Vercel

    clock icon

    Asked 1 year ago

    message

    0 Answers

    eye

    1 Views

    0

    I'm developing a Next.js project using JavaScript (not TypeScript) with Prisma for backend operations. The project is hosted on Vercel, and I'm using a PostgreSQL database hosted on Supabase.

    Problem: Prisma works fine in server components both locally and in production. However, it fails in API routes when deployed to Vercel. Locally, the API routes work as expected, but in production, I get a "prisma is undefined" error.

    Environment:

    Next.js version: 14.2.5 Prisma version: 5.19.0 @prisma/client version: 5.17.0 Vercel (for hosting) Supabase (for PostgreSQL database) Node.js version: (please specify the version you're using locally and on Vercel)

    Here's a simplified version of my API route where Prisma fails in production:

    // app/api/diaries/route.js
    import { NextResponse } from 'next/server';
    import prisma from "@/lib/prisma";
    
    export async function GET() {
      try {
        const diaries = await prisma.diary.findMany();
        return NextResponse.json(diaries);
      } catch (error) {
        console.error("Error fetching diaries:", error);
        return NextResponse.json({ error: 'Failed to fetch diaries', details: error.message }, { status: 500 });
      }
    }
    

    Here's a server component (page.js) where Prisma works correctly both locally and in production:

    // app/diaries/page.js
    import { getServerSession } from "next-auth/next";
    import { redirect } from "next/navigation";
    import Link from "next/link";
    import DiaryList from "./DiaryList";
    import prisma from "@/lib/prisma";
    
    export default async function DiaryPage() {
      const session = await getServerSession();
    
      if (!session) {
        redirect("/api/auth/signin");
      }
    
      const diaries = await prisma.diary.findMany({
        where: { userId: session.user.id },
        orderBy: { createdAt: "desc" },
      });
    
      return (
        <div className="container mx-auto px-4 py-8">
          <h1 className="text-3xl font-bold mb-6 text-gray-800">My Diaries</h1>
          <DiaryList diaries={diaries} />
          <Link href="/diaries/new" className="mt-6 inline-block bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600 transition-colors">
            Write New Diary
          </Link>
        </div>
      );
    }
    

    And here's how I'm initializing Prisma:

    // lib/prisma.js
    import { PrismaClient } from '@prisma/client'
    
    const prisma = new PrismaClient()
    if (process.env.NODE_ENV !== 'production') global.prisma = prisma
    
    export default prisma
    

    My build script in package.json is:

    "build": "prisma generate && prisma migrate deploy && next build"
    

    What I've Tried:

    Checked that the DATABASE_URL environment variable is correctly set in Vercel. Verified that the Prisma schema is up to date and migrations are applied. Confirmed that the issue only occurs in API routes, not in server components.

    Expected Behavior: The API routes should work in production as they do locally, with Prisma correctly initialized and able to query the database. Actual Behavior: In production, API routes fail with a "prisma is undefined" error, while they work fine locally and in server components.

    nextjs
    orm
    prisma

    Write your answer here

    0 Answers

    Menu

    Top Questions

    How to center a div?

    chevron

    How to do code parsing with React.js and NextJS?

    chevron

    How to get better at Nextjs?

    chevron

    Postgres: upgrade a user to be a superuser? ?

    chevron

    This is another test question

    chevron

    Popular Tags

    nextjs

    6

    React

    4

    next.js

    3

    reactjs

    3

    css

    3