How to Connect a cPanel Node.js App to a MySQL Database
To connect a Node.js app to MySQL on cPanel, you create the database and a user in cPanel, then connect from your app using a MySQL driver like mysql2 — ideally with a connection pool. The database runs locally on the same server, so your app connects to it on localhost.
Step 1: Create the database and user
In cPanel, use MySQL Databases to create a database, create a user, and add the user to the database with privileges — see creating a MySQL database and user. Note the full names (cPanel prefixes them with your account name).
Step 2: Install the driver
Add mysql2 to your app and install it — see installing npm packages.
Step 3: Connect with a pool
Use a connection pool for efficiency, with credentials from environment variables:
const pool = mysql.createPool({ host: 'localhost', user: process.env.DB_USER, password: process.env.DB_PASSWORD, database: process.env.DB_NAME });
The host is localhost because the database is on the same server as your app.
Step 4: Query safely
Always use parameterised queries to prevent SQL injection:
const [rows] = await pool.query('SELECT * FROM users WHERE id = ?', [id]);
Frequently asked questions
What host should I use to connect?
Use localhost, since the MySQL server runs on the same cPanel server as your app. Remote connections are a different, more involved setup and often restricted.
My connection is refused or access denied.
Check that the user is added to the database with privileges, and that the database and user names include the account prefix cPanel adds. A mismatch there is the usual cause.
Should I use a pool or a single connection?
A pool — it reuses connections efficiently and handles concurrency far better than a single connection, especially under load. See the connection pooling guide.
Was this article helpful?