Connection pooling helps your serverless app reuse database connections. This makes your app faster and avoids errors from opening too many connections.
0
0
Connection pooling for serverless in NextJS
Introduction
When your Next.js API routes connect to a database frequently.
When you want to avoid hitting database connection limits in serverless environments.
When your app needs to handle many quick requests without delay.
When you want to improve performance by reusing existing connections.
When your database provider supports connection pooling.
Syntax
NextJS
import { createPool } from 'mysql2/promise'; const pool = createPool({ host: 'localhost', user: 'user', password: 'password', database: 'mydb', waitForConnections: true, connectionLimit: 10, queueLimit: 0 }); export default pool;
This example uses mysql2/promise for MySQL connection pooling.
Adjust connectionLimit to control max simultaneous connections.
Examples
Pool with a max of 5 connections and queue limit of 10 requests waiting.
NextJS
import { createPool } from 'mysql2/promise'; const pool = createPool({ host: 'db.example.com', user: 'admin', password: 'secret', database: 'appdb', waitForConnections: true, connectionLimit: 5, queueLimit: 10 });
PostgreSQL pool example with max 20 connections and 30 seconds idle timeout.
NextJS
import { Pool } from 'pg'; const pool = new Pool({ connectionString: process.env.DATABASE_URL, max: 20, idleTimeoutMillis: 30000 });
Sample Program
This Next.js API route uses a connection pool to query the current time from the database. It reuses connections efficiently for each request.
NextJS
import { createPool } from 'mysql2/promise'; const pool = createPool({ host: 'localhost', user: 'root', password: 'password', database: 'testdb', waitForConnections: true, connectionLimit: 5, queueLimit: 0 }); export default async function handler(req, res) { try { const [rows] = await pool.query('SELECT NOW() AS now'); res.status(200).json({ time: rows[0].now }); } catch (error) { res.status(500).json({ error: 'Database query failed' }); } }
OutputSuccess
Important Notes
Serverless functions can start and stop often, so connection pooling helps avoid opening too many new connections.
Always close or release connections if you manage them manually, but pools handle this automatically.
Use environment variables to keep database credentials safe and configurable.
Summary
Connection pooling lets serverless apps reuse database connections.
This improves speed and prevents connection limits errors.
Use libraries like mysql2/promise or pg with pooling options.