Fix 'PrismaClient is unable to be run in the browser' in Next.js

By

Fix the Next.js error PrismaClient is unable to be run in the browser by keeping Prisma code and its import inside getStaticProps on a page route only.

~~~

This error means Prisma code ended up in your client-side JavaScript bundle. The fix is to make sure the Prisma import and every Prisma call live inside getStaticProps() (or getServerSideProps()) on a page route, so Next.js keeps them on the server.

Let me show you how I ran into it.

I ran into this error while working on a Next.js website:

PrismaClient is unable to be run in the browser

I had this page and it all worked fine until I commented one line in my code, in particular in my getStaticProps() method.

In that line I called a method from my Prisma instance, which I imported at the top of the page file.

Why this error happens

Prisma Client talks directly to your database. It opens a connection using your database credentials, and it relies on Node.js APIs to do so.

None of that can happen in the browser. And even if it could, you would be shipping your database credentials to every visitor. So Prisma refuses to run there, and throws this error instead.

Normally you never see it, because Next.js is smart about server-only code. It analyzes what you use inside getStaticProps() and getServerSideProps(), and strips that code from the frontend bundle. The Prisma import stays on the server.

But this only works as long as the import is actually used in one of those functions.

When I commented out the line in getStaticProps() where I used Prisma, Next.js could no longer tell the import was server-only. It included Prisma in my frontend code, and I got the error.

The fix

The solution was to also comment (or remove) the Prisma import at the top of the file.

The rule is: the import and its usage go together. If you remove the last usage inside getStaticProps(), remove the import too. When you add the usage back, add the import back.

When the error comes from a component

Also remember that getStaticProps() is only called on page routes, the files inside the pages folder. It does not work in other components.

So if this error comes from a component, you can’t fix it there. You have to move the data fetching up to the page route component, run Prisma inside its getStaticProps(), and pass the data down to the component as props.

Another option is to move the Prisma call into an API route, and have the component fetch from that endpoint. Either way, Prisma code only runs on the server.

Tagged: Next.js · All topics
~~~

Related posts about next: