prisma: PrismaClient is unable to be run in the browser.

Bug description

I’m getting an Error: PrismaClient is unable to be run in the browser.

Selection_013

How to reproduce

  1. Create new Node Project with npm init -y
  2. install dependencies npm i next react react-dom
  3. install prisma with npm i -D primsa and then npm i @prisma/client
  4. init prisma with npx primsa init
  5. change schema to :
generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

model Post {
  id        Int     @id @default(autoincrement())
  title     String
  content   String?
  published Boolean @default(false)
  author    String?
}

  1. push schema to postgresql with npx prisma db push --preview-feature
  2. create index.js like:
import {PrismaClient} from "@prisma/client"
export {PrismaClient} from "@prisma/client"

const prisma = new PrismaClient()

export default function Page(){
        return <div>Hello World</div>
}





  1. run server
  2. getting error

Expected behavior

Displaying Hello World but getting an error

Prisma information

Environment & setup

  • OS: Ubuntu 20.4
  • Database: PostgreSQL on Heroku
  • Node.js version: v10.19.0
  • Prisma version:2.19.0

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Comments: 35 (2 by maintainers)

Commits related to this issue

Most upvoted comments

I was having a similar issue. I think a solution is to only initialize the client once and on the server only.

import { Prisma, PrismaClient } from "@prisma/client";

declare global {
  namespace NodeJS {
    interface Global {
      prisma: PrismaClient;
    }
  }
}

let prisma: PrismaClient;

if (typeof window === "undefined") {
  if (process.env.NODE_ENV === "production") {
    prisma = new PrismaClient();
  } else {
    if (!global.prisma) {
      global.prisma = new PrismaClient();
    }

    prisma = global.prisma;
  }
}

export default prisma;

@fugohan You are trying to use Prisma on frontend which is not possible. Either use it in next js api routes: https://nextjs.org/docs/api-routes/introduction or use it in getServerSideProps or getStaticProps: https://nextjs.org/docs/basic-features/data-fetching#getserversideprops-server-side-rendering

Thought I’d chime in as my solution is different. Essentially the above sugggestions were breaking my tests. Jest seemed unable to infer that the prisma var declared and the let were the same variable resulting in a Duplicate declaration prisma error. I also wanted to be able to export the variable itself rather than export default to keep import type-checking. I had to update the declaration and was able to remove all the typescript and eslint exceptions:

import { PrismaClient } from '@prisma/client';

declare const global: Global & { prisma?: PrismaClient };

export let prisma: PrismaClient;

if (typeof window === 'undefined') {
  if (process.env['NODE_ENV'] === 'production') {
    prisma = new PrismaClient();
  } else {
    if (!global.prisma) {
      global.prisma = new PrismaClient();
    }
    prisma = global.prisma;
  }
}

None of the suggestions above are not working on Next.js v.13.2 😦 api routes transferred under App directory on this version.

Have you somehow fix this ? 😃

This was necessary for me for me in Next.js:

if (typeof window === "undefined") {
  ...
}
if (typeof window === "undefined") {
  if (process.env.NODE_ENV === "production") {
      prisma = new PrismaClient();
    } else {
      if (!global.prisma) {
        global.prisma = new PrismaClient();
      }
      prisma = global.prisma;
    }
}

You call the PrismaClient() into getStaticProps, and your error is solved. When you call the PrismaClient() component, you face an error.

import { PrismaClient } from '@prisma/client'



export async function getStaticProps() {
  const prisma = new PrismaClient()

  return {
    props : { }
  }
}

I encountered this error in my Nextjs ts project and was puzzled. Then I saw that I was exporting a function that I was using on the client from my custom ‘utilities’ directory, and from the same ‘utilities’ directory I was exporting the prisma client. So I moved the prisma client ( and other serverside modules ) to a custom ‘services’ directory. After that the error went away. (anecdotal/mayhelpsomeone).

I was able to accomplish this similarly by creating a global.d.ts file with

import { PrismaClient } from '@prisma/client';

declare global {
  var prisma: PrismaClient;
}

And using the same initialization.

import { PrismaClient } from "@prisma/client";

let prisma: PrismaClient;

if (typeof window === "undefined") {
  if (process.env.NODE_ENV === "production") {
    prisma = new PrismaClient();
  } else {
    if (!global.prisma) {
      global.prisma = new PrismaClient();
    }

    prisma = global.prisma;
  }
}

export default prisma;

However, I would get the error…

TS2454: Variable 'prisma' is used before being assigned.

I adjusted the code to initialize the variable to null, but that caused typing errors elsewhere.

let prisma: PrismaClient | null = null;

Doing this led to TS2531: Object is possible 'null' warnings in my API code (in my case NextJS API route)

  return await prisma.user.findFirst ({
    where: {
      accessCode: accessCode
    }
  });

I ended up adding a @ts-ignore to the export default prisma; line. I’m not sure if that’s really the right way to do it, but I wanted to share in case someone like me encountered Typescript errors following this approach and wanted to resolve them.

Facing same issue, with the help of the suggestions above… and the new docs I found here this is my /lib/prisma.ts in next.js

import { PrismaClient } from '@prisma/client'
declare global {
  // allow global `var` declarations
  // eslint-disable-next-line no-var
  var prisma: PrismaClient | undefined
}

let prisma: PrismaClient

if (typeof window === 'undefined') {
  if (process.env.NODE_ENV === 'production') {
    prisma = new PrismaClient()
  } else {
    if (!global.prisma) {
      global.prisma = new PrismaClient()
    }

    prisma = global.prisma
  }
}
//@ts-ignore
export default prisma

Example usage: import prisma from '../lib/prisma'

I had the experimental-edge runtime enabled in my Next.js config (resulting in the “unable to be run in the browser error”). None of the above solutions worked for me until I disabled that. At the time of writing I’m using the latest version of next (12.3.1) and @prisma/client (4.4.0). I did not need to use dynamic imports or a typeof window guard.

I didn’t know that I needed extra setup to get @prisma/client working with Next.js’s edge runtime. After going through the instructions at https://www.prisma.io/docs/data-platform/data-proxy, things are working now with the experimental-edge runtime enabled 🥳 But I still had to make sure I didn’t have fallbackNodePolyfills: false set as well.

Trying to use Prisma in edge functions without the data proxy (or being able to use both versions in the same app) doesn’t yet seem to be supported: https://github.com/prisma/prisma/issues/9928.

another possible solution without //@ts-ignore:

import { PrismaClient } from '@prisma/client'

// PrismaClient is attached to the `global` object in development to prevent
// exhausting your database connection limit.
//
// Learn more:
// https://pris.ly/d/help/next-js-best-practices

declare global {
  var prisma: PrismaClient | undefined
}

const prisma = global.prisma || new PrismaClient({
  log: ['error']
})

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

export default prisma

src: https://github.com/2color/next-prisma-data-proxy/blob/main/lib/prisma.ts PS: I also think that u should also either use getStaticProps or getServerSideProps or nextjs API routes as this comment said. https://www.prisma.io/nextjs#nextjs-tabs

I realized that the issue occurred because I forgot to use 'use server', as I was running a server action with Prisma.

@olserra You’re replying to a public issue thread. Details about access restrictions aren’t relevant to this issue; be careful not to post any sensitive info here.

I had this same issue inside getInitialProps when using import, as fix i am using require inside getInitialProps:

const db: PrismaClient = require('../lib/prisma').default

the lib/prisma file is from the docs as @josiext mentioned

same issue