Next.js › Database Integration with Next.js
How do you manage a database connection efficiently across many requests in a serverless Next.js deployment?
IntermediateAnswer
In serverless environments, creating a new database connection on every single request can quickly exhaust the database's connection limit, so you typically use a connection pooler or reuse a single client instance across requests by attaching it to a global variable during development.
// lib/db.js
let db;
if (process.env.NODE_ENV === 'production') {
db = new PrismaClient();
} else {
if (!global.db) global.db = new PrismaClient();
db = global.db;
}
export { db };Real-world example A high traffic application uses a connection pooling service alongside Prisma to prevent running out of available database connections during traffic spikes.