Last Updated : 11 Jul, 2025
Node.js is a powerful platform for building server-side applications, and MySQL is a widely used relational database. Connecting these two can enable developers to build robust, data-driven applications.
In this article, we'll explore how to connect a Node.js application with a MySQL database, covering the necessary setup, configuration, and basic CRUD (Create, Read, Update, Delete) operations.
Prerequisites:To Connect MySQL with the Node App we will be using the mysql npm package. After installing, configure the database credentials and establish the connection. Connect the database, handle errors perform queries to interact with the MySQL database using the Node App.
Steps to Connect MySQL with Node App Step 1: Open your terminal and create a new directory for your project.mkdir node-mysql-app cd node-mysql-appStep 2: Initialize a new Node.js project:
npm init -yStep 3: Install MySQL Package
Install the mysql
package, which is a Node.js driver for MySQL:
npm install mysqlStep 4: The updated dependencies in package.json file will look like
"dependencies": {Step 5: Database Connection
"mysql": "^2.18.1"
}
Create a Javascript file named server.js in the root of the project folder. Code for creating connection is as given below:
JavaScript
// Filename - server.js
// importing mysql module
const mysql = require('mysql');
// configurations for creating mysql connection
const connection = mysql.createConnection({
host: 'localhost', // host for connection
port: 3306, // default port for mysql is 3306
database: 'test', // database from which we want to connect our node application
user: 'root', // username of the mysql connection
password: 'root' // password of the mysql connection
});
// executing connection
connection.connect(function(err) {
if (err) {
console.log("error occurred while connecting");
} else {
console.log("connection created with mysql successfully");
}
});
Run the file server.js with following command as:
node server.jsConclusion
Connecting Node.js with MySQL is straightforward and powerful, enabling developers to build data-driven applications with ease. By following the steps outlined in this article, you can set up a basic Node.js application that interacts with a MySQL database, performing essential CRUD operations. This foundation can be expanded to suit more complex application requirements, including advanced querying, data validation, and secure authentication.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4