CodingNic

Build the Data Layer

Create a Shared Prisma Client

Build the Data Layer 12 min read

Create a Shared Prisma Client

Create a Shared Prisma Client

Route handlers and server-side application code should not each construct their own Prisma client.

Task

Create one shared Prisma client in lib/prisma.ts.

Use:

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

const globalForPrisma = globalThis as unknown as {
  prisma?: PrismaClient;
};

export const prisma =
  globalForPrisma.prisma ??
  new PrismaClient();

if (process.env.NODE_ENV !== "production") {
  globalForPrisma.prisma = prisma;
}

The development global prevents hot reloads from creating a new client on every module reload.

Use the Shared Client

Future server code should import:

ts
import { prisma } from "@/lib/prisma";

Do not instantiate new PrismaClient() inside individual route handlers.

Test

Run:

bash
npx prisma validate
npm run dev

The application should start normally. There does not need to be visible database-backed UI yet; that work begins in the next module.

Checkpoint

You now have one application-level Prisma client ready for the authentication and feature modules.

Module Complete

Readly has moved from mock-only data to a real persistence foundation:

text
Next.js application
       ↓
 shared Prisma client
       ↓
     PostgreSQL

Module 3 will use this foundation to build custom authentication and secure sessions.