How to use .env file in NodeJS MySQL?
Last Updated :
20 Aug, 2024
Environment variables are list of properties defined by key and value used for storing configurations data for instance the database credentials, api keys and so on. In the past, these values were directly coded into your applications’ code and were not flexible to change, but today we can store them in a. configuration file known as .env file which makes it secure and well organized manner in controlling the configurations settings.
Here, in this article, you have been initiated with the preparation of a node.js application that interacts with a MySQL database using environment variables put in a .env file. Further, in asymmetrical modes we will also describe how promises can be implemented with the mysql2 package.
Prerequisites
Steps to Create Node. js Application
Step 1: Create a Node.js application using the following command:
mkdir geeksforgeeks
cd geeksforgeeks
npm init -y
Step 2: Install the required modules using the following command:
npm install mysql2 dotenv
Step 3: Once you have created a Node.js environment, create a .env file in the root directory of your project with the following content:
DB_HOST=localhost
DB_USER=root
DB_PASSWORD=password
DB_DATABASE=geeksforgeeks
This file defines environment parameters that will be used to connect database.
Step 4: Create a db.js file in your project directory to establish the MySQL connection:
JavaScript
require('dotenv').config();
const mysql = require('mysql2');
const connection = mysql.createConnection({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_DATABASE,
});
connection.connect((err) => {
if (err) throw err;
console.log('Connected to MySQL database!');
});
module.exports = connection;
Project Structure:
Project StructureUpdated Dependencies:
{
"name": "geeksforgeeks",
"version": "1.0.0",
"main": "db.js",
"scripts": {
"start": "node db.js"
},
"license": "ISC",
"dependencies": {
"dotenv": "^16.4.5",
"mysql2": "^3.11.0"
}
}
Step 5: Run the Project
To start the application and connect to the MySQL database use the below command
npm start
or
node db.js
Example 1: Connecting to MySQL Database using .env file
To illustrate, in this example, let us show you how to connect to a MySQL database based on the environment variables set in a .env file.
JavaScript
require("dotenv").config();
const mysql = require("mysql2");
// Create MySQL connection
const connection = mysql.createConnection({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_DATABASE,
});
// Connect to the database
connection.connect((err) => {
if (err) throw err;
console.log("Connected to MySQL database!");
// Create 'users' table
const createTableQuery = `
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL
)
`;
connection.query(createTableQuery, (err, results) => {
if (err) throw err;
console.log("Users table created or already exists.");
// Insert data into 'users' table
const insertQuery = `
INSERT INTO users (name, email)
VALUES ('GeeksforGeeks', '[email protected]')
`;
connection.query(insertQuery, (err, results) => {
if (err) throw err;
console.log("Data inserted into 'users' table.");
connection.end(); // Close the connection
});
});
});
module.exports = connection;
Output: That is when the console will display the message:
Connected to MySQL database!
Users table created or already exists.
Data inserted into 'users' table.
Output
INSERTED Entry in table geeksforgeeksThis is to ensure that indeed we are connected to the MySQL database and all the environment variables set were as required.
Example 2: Promises with mysql2
JavaScript
require("dotenv").config();
const mysql = require("mysql2/promise");
// Create MySQL connection
const connectToDatabase = async () => {
try {
const connection = await mysql.createConnection({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_DATABASE,
});
console.log("Connected to MySQL database!");
return connection;
} catch (err) {
console.error("Error connecting to the database:", err);
throw err;
}
};
// Example usage
const setupDatabase = async () => {
try {
const connection = await connectToDatabase();
// Create 'users' table
const createTableQuery = `
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL
)
`;
await connection.execute(createTableQuery);
console.log("Users table created or already exists.");
// Insert data into 'users' table
const insertQuery = `
INSERT INTO users (name, email)
VALUES ('GeeksforGeeks', '[email protected]')
`;
await connection.execute(insertQuery);
console.log("Data inserted into 'users' table.");
connection.end(); // Close the connection
} catch (err) {
console.error("Error setting up the database:", err);
}
};
setupDatabase();
Output: On successfully executing the console will show the day of the event as follows.
Connected to MySQL database!
Users table created or already exists.
Data inserted into 'users' table.
Ouput
INSERTED Entry in Table geeksforgeeksTo use promises with mysql2 makes the code more maintainable and easier to comprehend, especially when handling several concurrent operations.
Conclusion
Utilizing a .env file in Node.js and mysql2, the process of the configuration of environment-specific variables, for example, database credentials, is more manageable. The dotenv package, together with the promise-based nature of mysql2, avoids using raw queries and complexities and simplifies the creation of the tables and insertion of data.
Similar Reads
How to Create and Use Functions in MySQL with NodeJS?
We will learn how to create and use functions in MySQL with Node.js. MySQL functions allow encapsulating complex calculations and business logic within the database, which can then be called from Node.js applications. This method is particularly useful for reusing SQL code and maintaining a clean ap
3 min read
How to Setup View Engine in Node.js ?
View engines are useful for rendering web pages. There are many view engines available in the market like Mustache, Handlebars, EJS, etc but the most popular among them is EJS which simply stands for Embedded JavaScript. It is a simple templating language/engine that lets its user generate HTML with
2 min read
How To Use An ES6 Import In Node.js?
To use an ES6 import in Node.js, you need to make some configurations to support ES6 modules. While Node.js was originally built around the CommonJS module system (require() and module.exports), modern JavaScript development prefers using the ES6 module syntax (import and export). Node.js now suppor
4 min read
How to Handle MySQL Connection Errors in NodeJS?
Dealing with MySQL connection errors requires you to look at issues related to establishing, maintaining, and closing connections to the MySQL database. This includes initial connection failure, connection drop detection and recovery, and error handling during query execution. Effective error handli
2 min read
How to Use Transactions in MySQL with NodeJS?
Transactions in MySQL are used to execute a series of operations as a single unit of work, ensuring that all operations either succeed or fail together. This is crucial in maintaining data integrity, especially when dealing with complex operations that involve multiple database queries. In Node.js,
2 min read
How to hide API key in Node ?
When building applications that interact with third-party services or APIs, using API keys for authentication and authorization is common. However, exposing these keys in your codebase can pose significant security risks. Malicious actors could misuse your API keys, leading to unauthorized access, d
2 min read
Node.js MySQL FIND_IN_SET() Function
FIND_IN_SET() function is a built-in function in MySQL that is used to get the position of the first occurrence of value string in a list of strings separated by comma(','). Syntax: FIND_IN_SET(value, list_of_string)Parameters: It takes two parameters as follows: value: It is the value to be searche
2 min read
How to Create a Dockerfile in Node.js ?
A Dockerfile is a text document that contains all the commands a user could call on the command line to assemble an image. It is something like a shellscript that gathers multiple commands into a single document to fulfill a single task. Prerequisite: Before you can Dockerize any application, you ne
4 min read
How to use EcmaScript Modules in Node.js ?
Using ECMAScript Modules (ES Modules or ESM) in Node.js allows you to take advantage of modern JavaScript syntax for organizing and managing your code. ECMAScript Modules provide a more structured and standardized way to work with modules compared to CommonJS, which has been traditionally used in No
2 min read
How To Install MYSQL Using Ansible Playbook ?
Introducing MySQL physically on different servers can be a tedious and mistake-inclined process. Be that as it may, with Ansible, an open-source mechanization apparatus, you can computerize the establishment and setup of MySQL across your framework effectively and proficiently. By allowing you to de
6 min read