Applications and operations
Connect to MySQL from Node.js
Optionally connect from Node.js with mysql2, environment-based credentials, a bounded pool, and explicit connection timeouts.
The application lessons use Node.js as an optional track. You can follow the database and operations lessons without it.
mysql2 is the actively maintained MySQL driver for Node.js. It speaks the MySQL protocol directly, supports prepared statements, and ships a promise API, so you can use await instead of callbacks.
Install it:
npm install mysql2
Create a bounded pool from environment variables:
import mysql from 'mysql2/promise'
export const pool = mysql.createPool({
host: process.env.DB_HOST,
port: Number(process.env.DB_PORT ?? 3306),
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
waitForConnections: true,
connectionLimit: 5,
queueLimit: 20,
connectTimeout: 5000,
enableKeepAlive: true,
})
A pool is the right default even for small applications. It reuses connections instead of paying the TCP and authentication handshake on every query, and connectionLimit caps how many connections this process can open. Five connections is an example budget, not a universal value. Count every application replica before choosing the limit.
Verify the connection before building anything on top of it:
const [rows] = await pool.query('SELECT VERSION() AS version')
console.log(rows[0].version) // 8.4.x
If the credentials are wrong, or the account host does not match where your code runs from, the driver rejects with ER_ACCESS_DENIED_ERROR, the same error 1045 you saw in the client lessons. Test the identical host, port, and account with the mysql command-line client to decide whether the problem is the driver configuration or the account itself.
Call await pool.end() when a script or worker shuts down. It waits for queries in flight, then closes every connection. A long-running web process keeps the pool open until its shutdown hook runs. Without pool.end(), a finished script keeps the event loop alive and the process never exits — that hanging script is usually the first pool bug people meet.
Lesson completed