Ugo
Ugo

Sharing a Prisma Instance Between Projects

Prisma is a popular ORM for JavaScript and TypeScript, but sharing an instance of it between multiple microservices can be tricky. Here's a solution to this problem that avoids the maintainability nightmare of copy-pasting the Prisma schema into all of your projects.

Setting Up a New Project


To start, create a new project and follow the Prisma Quickstart instructions. Alternatively, you can use the following commands:

mkdir prisma-instance
cd prisma-instance
pnpm init
pnpm add prisma typescript ts-node @types/node -D
npx tsc --init
pnpm prisma init
pnpm add @prisma/client

Next, copy your existing Prisma folder containing your schema and migrations (if applicable) from your project to the root of the new project.

Then, update your tsconfig.json file as follows:

{
  "compilerOptions": {
    "sourceMap": true,
    "outDir": "dist",
    "strict": true,
    "lib": ["esnext"],
    "esModuleInterop": true
  }
}

Inside your schema.prisma file, add output = "client" to the generator:

generator client {
    provider = "prisma-client-js"
    output   = "client"
}

Run npx prisma generate, which will create a client directory inside your prisma directory with the generated client inside it.

Next, create a src directory in the root of your project and add an index.ts and index.d.ts file:

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

let prisma: PrismaClient | undefined;

export const getPrisma = () => {
  if (!prisma) {
    prisma = new PrismaClient();
  }
  return prisma;
};
import { PrismaClient } from '../prisma/client';

export * from '../prisma/client/index.d';
export function getPrisma(): PrismaClient;

Add a postinstall script to your package.json file:

"scripts": {
    "postinstall": "tsc && cp src/index.d.ts dist/index.d.ts && npx prisma@4.7.1 generate"
}

Finally, publish your private package using npm or GitHub.

Using the Private Prisma Package in Next.js

If one of the projects you plan to use Prisma in is a Next.js project, you may encounter some issues. To resolve them:

  1. Install the private package with pnpm add @your-name/prisma-instance.

  2. In your .npmrc file, add these two lines:

public-hoist-pattern[]=*prisma*
node-linker=hoisted
  1. If you’re using the app directory in Next 13, open your next.config.js and add your Prisma package to serverComponentsExternalPackages:
experimental: {
    appDir: true,
    serverComponentsExternalPackages: ['@your-name/prisma-instance'],
  },

With these steps, you should now be able to share a single instance of Prisma between multiple microservices, improving the maintainability of your projects. Happy coding!

Send Ugo a reply about this page
Back to profile