@@ -2,16 +2,49 @@ import { PrismaClient } from "@prisma/client";
22
33import { env } from "@/env" ;
44
5- const createPrismaClient = ( ) =>
6- new PrismaClient ( {
5+ const createPrismaClient = ( ) => {
6+ const client = new PrismaClient ( {
77 log :
88 env . NODE_ENV === "development" ? [ "query" , "error" , "warn" ] : [ "error" ] ,
99 } ) ;
1010
11+ // In serverless environments (Vercel), we want to avoid eager connection
12+ // Prisma will connect lazily on first query, which is better for cold starts
13+ // Don't call $connect() here - let Prisma handle connections on-demand
14+
15+ return client ;
16+ } ;
17+
1118const globalForPrisma = globalThis as unknown as {
1219 prisma : ReturnType < typeof createPrismaClient > | undefined ;
1320} ;
1421
15- export const db = globalForPrisma . prisma ?? createPrismaClient ( ) ;
22+ // Reuse Prisma client across invocations to optimize connection pooling
23+ // In Vercel serverless, the same container may handle multiple requests
24+ // Reusing the client prevents creating new connections for each request
25+ export const db =
26+ globalForPrisma . prisma ?? createPrismaClient ( ) ;
1627
17- if ( env . NODE_ENV !== "production" ) globalForPrisma . prisma = db ;
28+ // Store in globalThis for reuse across all environments
29+ // This is especially important in serverless where the same container
30+ // may handle multiple requests, allowing connection reuse
31+ if ( ! globalForPrisma . prisma ) {
32+ globalForPrisma . prisma = db ;
33+ }
34+
35+ // Graceful shutdown handling
36+ if ( typeof process !== "undefined" ) {
37+ process . on ( "beforeExit" , async ( ) => {
38+ await db . $disconnect ( ) ;
39+ } ) ;
40+
41+ process . on ( "SIGINT" , async ( ) => {
42+ await db . $disconnect ( ) ;
43+ process . exit ( 0 ) ;
44+ } ) ;
45+
46+ process . on ( "SIGTERM" , async ( ) => {
47+ await db . $disconnect ( ) ;
48+ process . exit ( 0 ) ;
49+ } ) ;
50+ }
0 commit comments