Sami Ali
Sami Ali

Reputation: 147

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:

Upvotes: 1

Views: 2729

Answers (3)

Oscar Corona
Oscar Corona

Reputation: 720

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;

Upvotes: 1

Danny
Danny

Reputation: 11

You need to use 'use server' directive at top of your server action file

Upvotes: 1

U Ang
U Ang

Reputation: 108

Seems you are invoking PrismaClient in client side even if the code is run async model. Pls try to move Prisma code into server api, then, call the api in the client.

Upvotes: 1

Related Questions