How to Connect to MySQL From Node.js
Connect to MySQL 8.4 from Node.js 26 with mysql2, use a promise pool, run prepared statements and transactions, and handle duplicate key errors.

Like PostgreSQL, MySQL needs a driver in Node.js, and the standard choice is mysql2. It is a fast, actively maintained client that supports promises, prepared statements, connection pools and TLS, and it is compatible with MySQL 8.4 LTS and MariaDB. This post covers installing it, opening a pool, running queries safely with placeholders, the difference between query() and execute(), reading insert results, transactions, error handling and shutdown. The examples use Node.js 26 with ES modules and the promise interface. The driver's documentation is at sidorares.github.io/node-mysql2.
Install and import
npm install mysql2The package has two interfaces: a callback one and a promise one. Import the promise one from the mysql2/promise path, so you can use await.
import mysql from "mysql2/promise";
console.log(typeof mysql.createPool);
console.log(typeof mysql.createConnection);function
functionA single connection
createConnection opens one connection. Use it for scripts and migrations. You pass either an options object or a connection URI.
import mysql from "mysql2/promise";
const connection = await mysql.createConnection({
host: "127.0.0.1",
port: 3306,
user: "app",
password: process.env.DB_PASSWORD,
database: "shop",
});
const [rows] = await connection.query("SELECT 1 + 1 AS sum");
console.log(rows);
await connection.end();[ { sum: 2 } ]Every query returns a tuple of [result, fields]. The first element is the data, and the second describes the columns. Most code destructures just the first. Without connection.end(), the process stays alive.
A pool for servers
A pool reuses connections across requests, which avoids the cost of authenticating each time and keeps you inside the server's max_connections limit. createPool takes the same options plus pool settings.
import mysql from "mysql2/promise";
export const pool = mysql.createPool({
host: "127.0.0.1",
user: "app",
password: process.env.DB_PASSWORD,
database: "shop",
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0,
namedPlaceholders: true,
});connectionLimit is the maximum number of open connections, and the default is 10. When all are busy and waitForConnections is true, new requests queue, with queueLimit: 0 meaning the queue is unbounded. For a service with strict latency goals, set a limit so overload fails fast instead of piling up. The pool object has query(), execute() and getConnection().
Safe queries with placeholders
Never build SQL with string concatenation. Use ? placeholders and pass the values in an array. Both query() and execute() accept them, but they work differently, and the difference matters.
query() builds the final SQL on the client by escaping the values, then sends it as a text query. execute() uses a real server-side prepared statement: the SQL and the values travel separately, and the statement is cached per connection for reuse. Prefer execute() for application queries, and use query() for statements that cannot be prepared, or when you need to expand a list with IN (?).
import { pool } from "./pool.js";
await pool.execute(`
CREATE TABLE IF NOT EXISTS products (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
sku VARCHAR(40) NOT NULL UNIQUE,
name VARCHAR(120) NOT NULL,
price DECIMAL(10,2) NOT NULL
)
`);
const [result] = await pool.execute(
"INSERT INTO products (sku, name, price) VALUES (?, ?, ?)",
["MUG-01", "Mug", 12.5],
);
console.log(result.affectedRows);
console.log(result.insertId);
const [rows] = await pool.execute("SELECT name, price FROM products WHERE sku = ?", [
"MUG-01",
]);
console.log(rows);
await pool.end();1
1
[ { name: 'Mug', price: '12.50' } ]For an insert, the first element of the result is a header object with affectedRows and insertId. The id shown assumes an empty table. Notice that price comes back as the string '12.50': DECIMAL values are returned as strings by default so that no precision is lost to floating-point numbers. Convert them deliberately, or keep money as integer cents in the database.
execute() is strict about undefined. Passing undefined as a parameter throws an error, because there is no SQL equivalent. Pass null for a null value.
Named placeholders
When a statement has many values, positional markers become hard to match up. With namedPlaceholders: true on the pool, use :name markers and pass an object.
import { pool } from "./pool.js";
const [rows] = await pool.execute(
"SELECT id, name FROM products WHERE price < :max AND name LIKE :pattern",
{ max: 20, pattern: "%Mug%" },
);
console.log(rows);
await pool.end();[ { id: 1, name: 'Mug' } ]Lists with IN
A placeholder stands for one value, so WHERE id IN (?) with an array does not work in execute(). The query() method expands arrays into comma-separated lists on the client, which is the one place where it is the right choice.
import { pool } from "./pool.js";
const ids = [1, 2, 3];
const [rows] = await pool.query("SELECT id FROM products WHERE id IN (?)", [ids]);
console.log(rows.map((row) => row.id));
await pool.end();[ 1 ]The array is wrapped in another array, because the outer array is the list of parameters and the inner one is the single parameter that expands. With only one product in the table, only id 1 matches. If the list could be empty, handle that case before building the query, since IN () is a syntax error.
Transactions
A transaction must run on one connection, so take one from the pool, start the transaction on it and release it when done.
import { pool } from "./pool.js";
async function placeOrder(productId, quantity) {
const connection = await pool.getConnection();
try {
await connection.beginTransaction();
await connection.execute(
"UPDATE stock SET quantity = quantity - ? WHERE product_id = ? AND quantity >= ?",
[quantity, productId, quantity],
);
await connection.execute(
"INSERT INTO orders (product_id, quantity) VALUES (?, ?)",
[productId, quantity],
);
await connection.commit();
} catch (error) {
await connection.rollback();
throw error;
} finally {
connection.release();
}
}
await placeOrder(1, 2);
console.log("ordered");
await pool.end();orderedThis assumes stock and orders tables exist. If either statement fails, the rollback restores the stock. The finally block returns the connection to the pool, and forgetting it leaks the connection until the pool is exhausted. Note that the quantity >= ? guard does not by itself fail when stock is low, it just updates nothing, so check affectedRows on the first statement and throw if it is zero.
Handling errors
MySQL errors carry a code string and an errno number. Match on those instead of parsing the message.
import { pool } from "./pool.js";
async function addProduct(sku, name, price) {
try {
await pool.execute("INSERT INTO products (sku, name, price) VALUES (?, ?, ?)", [
sku,
name,
price,
]);
return "added";
} catch (error) {
if (error.code === "ER_DUP_ENTRY") return "duplicate sku";
throw error;
}
}
console.log(await addProduct("CAP-01", "Cap", 9));
console.log(await addProduct("CAP-01", "Cap", 9));
await pool.end();added
duplicate skuER_DUP_ENTRY is error number 1062, raised when a unique key already exists. Other useful codes are ER_NO_REFERENCED_ROW_2 for a missing foreign key target, ER_LOCK_DEADLOCK for a deadlock that should be retried, and PROTOCOL_CONNECTION_LOST or ECONNRESET when the connection dropped.
Authentication and TLS
MySQL 8.4 uses the caching_sha2_password authentication plugin by default, and mysql2 supports it. On a connection without TLS, the first login may need the server's public key, so for production use TLS, which also protects your data on the wire.
import { readFileSync } from "node:fs";
import mysql from "mysql2/promise";
const pool = mysql.createPool({
uri: process.env.DATABASE_URL,
ssl: {
ca: readFileSync("./certs/ca.pem", "utf8"),
rejectUnauthorized: true,
},
});
console.log(typeof pool.execute);
await pool.end();functionThe uri option takes the form mysql://user:password@host:3306/database.
Shutdown
Close the pool when the process stops, after you have stopped accepting new work. The pattern is the same as for any resource, and the graceful shutdown post shows the order of operations.
import { pool } from "./pool.js";
process.on("SIGTERM", async () => {
await pool.end();
process.exit(0);
});Keeping the pool healthy
A pool is only useful if connections go back to it. Every getConnection() must be paired with release(), ideally in a finally block, and code that only calls pool.query() or pool.execute() is safe because the pool releases those connections itself. Prefer that form whenever a statement does not need a transaction. MySQL also closes idle connections after wait_timeout, so a connection that sat unused overnight may be dead when the next request picks it up. The pool detects many of these cases and replaces the connection, and you can reduce the chance of surprise by enabling keep-alive on the pool options and by retrying a statement once when you see a connection reset error on a read. Never retry a write blindly, since the first attempt may have reached the server before the connection dropped, and a second attempt could insert a duplicate row.
Finally, give the pool a modest connectionLimit and remember the arithmetic: the limit multiplied by the number of application instances must stay below the server's max_connections, with room left for your migration tool and for administrators.


