I’m using Prisma in a Next.js app, and I want to ensure that the Prisma client is only instantiated on the server-side and never exposed to the client. However, I’m concerned that in my current setup, I might be accidentally exposing the prisma variable to the client.
Here’s how I’m currently managing the Prisma client (prisma.ts):
import { PrismaClient } from '@prisma/client'
const prismaClientSingleton = () => {
return new PrismaClient()
}
declare const globalThis: {
prismaGlobal: ReturnType<typeof prismaClientSingleton>;
} & typeof global;
export const prisma = globalThis.prismaGlobal ?? prismaClientSingleton()
if (process.env.NODE_ENV !== 'production') globalThis.prismaGlobal = prisma
I want to ensure that the Prisma client is only created on the server side and make sure that the prisma variable is not exposed to the client-side (e.g., through Next.js’s bundling process).
I thought about adding the “use server” statement, but files that have this statement can only export asynchronous functions.
Should I make an async function getPrisma()
that returns an instance of PrismaClient?
I don’t know how NextJS works with files that doesn’t has the “use server” statement.
What’s the safest way to manage PrismaClient in a Next.js application while ensuring it is never exposed to the client-side code?
Is this even a problem in NextJS? Should I worry about this or does NextJS handle it automatically?
It should be noted that I am only importing and using the prism instance in files that do have the “use server” statement.