Pre-establish readiness
Application startup
Prisma · Module
$connect() explicitly establishes Prisma Client's connection to the data source. It is usually unnecessary because Prisma connects lazily on the first query, but it can prepare the connection before requests arrive.
$connect() explicitly opens Prisma Client's connection to the data source before queries run. Prisma normally connects lazily on the first request, so explicit connection is mainly useful when startup should establish readiness before handling work.
await prisma.$connect()A promise that fulfills when Prisma Client has connected to the data source.
$connect() for opening the data-source connection and $disconnect() for closing it.$connect() is usually unnecessary because Prisma Client connects automatically when the first query is made.$connect() call.import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();
async function main() {
await prisma.$connect();
try {
console.log(await prisma.user.findMany());
} finally {
await prisma.$disconnect();
}
}
main().catch(console.error);Connect before the first query, then disconnect when the program finishes.
Application startup
Latency-sensitive first request
Connection verification
$connect() do?$connect() explicitly establishes Prisma Client's connection to the data source. Normally, Prisma invokes it implicitly when the first API request or query occurs.
Follow-up: Why call it explicitly? It can move connection setup to startup so the first user request does not pay the lazy-connection cost.
$connect() required before every query?It is generally optional because Prisma Client uses lazy connection behavior. The first query opens the connection automatically if the client has not already connected.
Follow-up: What lifecycle method complements it? $disconnect() closes the client and its database connections when they are no longer needed.
$connect() useful?Call $connect() during application startup when the application needs to establish the data-source connection before serving requests. This is useful when the first request must respond immediately.
Follow-up: How should a short-lived script clean up? Use a finally block to call $disconnect() after work completes, including when the work fails.
$disconnect()PrismaClientconnection poollazy connect