Connect MySQL with Node JS
Connecting MySQL with Node.js is a common requirement for developers working on server-side applications. If you’re new to this or stumbled upon this article out of curiosity, here’s a simple explanation: Node.js is a JavaScript runtime that enables you to run JavaScript on the server instead of the client’s browser, while MySQL is a relational database management system (RDBMS) that uses Structured Query Language (SQL) to manage and manipulate data efficiently. With these two tools, you can create dynamic and data-driven web applications.
Before we dive into the details, ensure you have Node.js and MySQL installed on your system. If not, you can download Node.js from https://nodejs.org/ and MySQL from https://www.mysql.com/downloads/. Once you have both installed, you’ll need the mysql2 package to connect Node.js with MySQL. You can install it using the command npm install mysql2 in your terminal. Next, create a database in MySQL (in this example, we’ve named it emailSign) and a file named app.js, where we’ll write the script to establish the connection.
In the app.js file, start by loading the dotenv package to securely manage sensitive information like database passwords. This can be done by adding require('dotenv').config() at the beginning of your script. Then, use the mysql2 package to create a connection to your database. Here’s how the code looks:
require('dotenv').config();
const mysql = require('mysql2');
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: process.env.MySql_password,
database: 'emailSign',
});
Instead of hardcoding the password in your code, store it securely in a .env file. This is a simple text file where you can define environment variables. For example, your .env file might contain the line MySql_password=your_password_here. This approach is highly recommended for security purposes, as it prevents sensitive data from being exposed in your codebase. To use the dotenv package, you need to install it first by running npm install dotenv --save in your terminal. After setting up the .env file and writing the connection script, you can run the script using the command node app.js in your terminal. If everything is configured correctly, your Node.js application will successfully connect to the MySQL database. Congratulations! You’ve just integrated MySQL with Node.js.
No comments yet
Sign in to leave a comment.
