mysql2/promise Connection PoolsNode.js connects to MySQL databases cleanly using the mysql2/promise package, which adds async / await support, native prepared statements, and built-in connection pooling. Using a connection pool instead of a single connection lets your server handle concurrent API requests reliably without reconnecting on every route call.
Create one shared pool module (db.js) configured from environment variables, then import it across your routes and repositories. Set connectionLimit sensibly (commonly 10 to 20) and keep waitForConnections: true so traffic bursts queue briefly instead of failing immediately.
import mysql from 'mysql2/promise';
export const pool = mysql.createPool({
host: process.env.DB_HOST || '127.0.0.1',
port: Number(process.env.DB_PORT || 3306),
user: process.env.DB_USER || 'app_user',
password: process.env.DB_PASSWORD || '',
database: process.env.DB_NAME || 'kodersolution_demo',
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0,
charset: 'utf8mb4',
});
async function checkDatabaseHealth() {
const [rows] = await pool.execute('SELECT 1 AS ok');
console.log('MySQL ready:', rows[0].ok === 1);
}
checkDatabaseHealth().catch((err) => console.error('MySQL error:', err.message));
pool.execute() vs pool.query()pool.execute(sql, params) compiles a real server-side MySQL prepared statement and caches it per connection—making it the best default for parameterized queries. Notice that pool.execute() returns a tuple [rows, fields], so array destructuring (const [rows] = await pool.execute(...)) gives you the result array directly.
mysql.createConnection() inside every HTTP handler: TCP + MySQL authentication handshakes add latency and leak connections if an error skips end(). Use a shared createPool().mysql v2 package with MySQL 8+: The legacy mysql npm package lacks caching_sha2_password auth support and native promises. Standardize on mysql2/promise.await pool.end() on shutdown: Close the pool cleanly inside your SIGTERM handler so active queries finish before the container exits.pool.execute()—do I need to release the connection manually?No. Calling pool.execute() or pool.query() directly on the pool acquires a connection, runs the query, and automatically releases it back to the pool. You only call conn.release() when checking out a dedicated connection via await pool.getConnection() for transactions.
utf8mb4 in mysql2 configuration?utf8mb4 preserves 4-byte Unicode characters like emojis and international scripts without turning them into ?.
mysql2/promise?Call const conn = await pool.getConnection(), run await conn.beginTransaction(), execute your queries on conn, call await conn.commit() (or rollback() on error), and always call conn.release() in finally.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.