node.jsreactjsnext.jsprisma

PrismaClient Error: "PrismaClient is unable to be run in the browser" in Next.js with next-auth/react


I'm building a Next.js application and using the next-auth/react package for authentication. I have a server-side function that uses PrismaClient to fetch the current user's information based on their email. However, when I try to run this function, I encounter the following error:

enter image description here

I've checked my code and setup, and I'm confident that I'm using Prisma on the server-side. Here's the relevant code:

import { getSession, useSession } from "next-auth/react";
import prisma from '@/app/libs/prismadb';

const getCurrentUser = async () => {
try {
const session = await getSession();

if (!session?.user?.email) {
return null;
        }

const currentUser = await prisma.user.findUnique({
where: {
email: session.user.email as string
            }
        });

console.log("Current User is found:", currentUser);

if (!currentUser) {
return null;
        }

return currentUser;
catch (error) {
console.log(error);
return null;
    }
}

export default getCurrentUser;

I've verified that my prismadb configuration is set up correctly, and I'm using the correct versions of the relevant packages. I've also ensured that this code is running on the server side.

I'm not sure why I'm still getting this error even though I'm using Prisma in a server-side context. Is there something specific I might be missing in my setup? Any suggestions or insights would be greatly appreciated!

I've already taken the following steps to troubleshoot the issue:


Solution

  • Here the possible solution:

    actions/user.ts

    "use server"
    import { getSession, useSession } from "next-auth/react";
    import prisma from '@/app/libs/prismadb';
    
    const getCurrentUser = async () => {
    try {
    const session = await getSession();
    
    if (!session?.user?.email) {
    return null;
            }
    
    const currentUser = await prisma.user.findUnique({
    where: {
    email: session.user.email as string
                }
            });
    
    console.log("Current User is found:", currentUser);
    
    if (!currentUser) {
    return null;
            }
    
    return currentUser;
    catch (error) {
    console.log(error);
    return null;
        }
    }
    
    export default getCurrentUser;