Problem Statement
How do you connect to a database in Next.js and what are the best practices for connection pooling?
Explanation
Use database clients like Prisma, Drizzle ORM, or direct drivers like pg for PostgreSQL or mysql2 for MySQL, and create a singleton instance of the client to reuse across requests avoiding connection exhaustion. For serverless environments like Vercel, use connection pooling services like PgBouncer, Supabase, or PlanetScale that manage connections efficiently, or use HTTP-based database clients like Prisma Data Proxy or Turso that don't require persistent connections. Best practices include creating a single database client instance in a module that exports it for reuse, never creating new connections on each request, using environment variables for connection strings, implementing proper error handling and timeouts, and considering edge-compatible databases when using Edge Runtime. For App Router, you can query databases directly in Server Components without API routes, but ensure you're not creating multiple connections and handle connection errors gracefully with fallbacks or error boundaries.