Connecting to a Database
Connecting to a Database
Express is database-agnostic. You can connect to any database by installing the appropriate driver or ORM. The most common choices in the Node.js ecosystem are Prisma (type-safe ORM), Drizzle (lightweight ORM), Mongoose (MongoDB ODM), and raw pg for PostgreSQL.
Pattern: Create a Singleton Client
Create a single database client instance and export it. Importing it in multiple route files reuses the same connection pool rather than opening a new connection per request.
// src/lib/db.ts (Prisma example)
import { PrismaClient } from "@prisma/client";
declare global {
// eslint-disable-next-line no-var
var __prisma: PrismaClient | undefined;
}
export const db = globalThis.__prisma ?? new PrismaClient();
if (process.env.NODE_ENV !== "production") {
globalThis.__prisma = db;
}The global assignment prevents hot-reload from opening a new Prisma client on every file change during development, which would exhaust the connection pool.
Prisma requires a schema.prisma file that defines your data model, and you run npx prisma migrate dev to generate and apply SQL migrations. CPCODELAB backend modules use Prisma with PostgreSQL as the default stack.