#Prisma best practices for PrismaClient setup?

1 messages · Page 1 of 1 (latest)

azure cradle
#

I keep seeing this warning in my new app:

warn(prisma-client) This is the 10th instance of Prisma Client being started. Make sure this is intentional

How closely should I pay attention to this? I'm assuming I'm doing something wrong here. My typical setup looks like this:

export let loader = async({ params }) => {
  const prisma = new PrismaClient();
  await prisma.$connect();
  const post = await prisma.post.findFirst({
    where: {
      id: parseInt(params.postId)
    }
  })
  prisma.$disconnect();
  return post;
}

Should i initial PrismaClient only 1 time. Is that the purpose of the warning?

#

Prisma best practices for PrismaClient setup?

copper phoenix
#

Yep, here's a code snippet you can use

import { PrismaClient } from "@prisma/client";
import invariant from "tiny-invariant";

let prisma: PrismaClient;

declare global {
  var __db__: PrismaClient;
}

// this is needed because in development we don't want to restart
// the server with every change, but we want to make sure we don't
// create a new connection to the DB with every change either.
// in production we'll have a single connection to the DB.
if (process.env.NODE_ENV === "production") {
  prisma = getClient();
} else {
  if (!global.__db__) {
    global.__db__ = getClient();
  }
  prisma = global.__db__;
}

function getClient() {
  const { DATABASE_URL } = process.env;
  invariant(typeof DATABASE_URL === "string", "DATABASE_URL env var not set");

  const databaseUrl = new URL(DATABASE_URL);

  console.info(`🔌 setting up prisma client to ${databaseUrl.host}`);
  // NOTE: during development if you change anything in this function, remember
  // that this only runs once per server restart and won't automatically be
  // re-run per request like everything else is. So if you need to change
  // something in this file, you'll need to manually restart the server.
  const client = new PrismaClient();
  // connect eagerly
  client.$connect();

  return client;
}

export { prisma, prisma as db };