Zahra Golpa
Zahra Golpa

Reputation: 177

How to add database environment variables to Javascript

I want to add my database environment variables to a .env file and use that file in my Javascript program in order to create a connection to my database using Node.js.

So here is my database info which I use to create connection with:

var con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "my password",
  database: "mydatabase"
});

Then I try to check if I am connected to my database using these lines:

(It should print "Connected!").

con.connect(function(err) {   
  if (err) throw err;
  console.log("Connected!");
});

I want to put the first block of code in another file and require that file in my Node.js program.

How should I do this? How should I require the file? Thank you in advance :)

Upvotes: 2

Views: 8991

Answers (3)

Mohammad Ali Abdullah
Mohammad Ali Abdullah

Reputation: 331

Using dotenv package. Install dotenv package.

npm i dotenv

Create a new .env file in project root directory.

touch .env

Add environment variables to .env file

API_HOST=HOST-PLACEHOLDER-URL
API_KEY=TOP-SECRET
APP_NAME=node_crud
APP_ENV=local
APP_KEY=base64:RIjL2Uw/Wdve+HJEvRNp6LHhzoHtLbplQcUp60CBIvs=
APP_DEBUG=true
APP_URL=http://localhost
LOG_CHANNEL=stack
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=node_restapi
DB_USERNAME=root
DB_PASSWORD=
PORT = 5000

Add config/database.js file

const dotenv = require('dotenv');
const mysql = require('mysql');

// configraration with env. 
dotenv.config();
module.exports = mysql.createConnection({
host: process.env.DB_HOST,
user: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD, 
database: process.env.DB_DATABASE 
});

config/database.js connect with app.js file

// Database Connection
const conn = require('./config/database');
// Shows Mysql Connect
conn.connect((err) =>{
if(err) throw err;
console.log('Mysql Connected with App...');
});

enter image description here

  • A .env file is needed for a clean separation of environment-specific configurations.
  • The dotenv packaged is used to read a .env file at runtime containing environment variables and append them on the process.env object.
  • Creating an example for a .env file to document the mandatory variables speeds up project setup time.
  • Never commit a .env file to version control.

Upvotes: 0

Peter
Peter

Reputation: 2927

I suggest using dotenv package.

Taken straight from the readme:

  1. As early as possible in your application, require and configure dotenv.

    require('dotenv').config()

  2. Create a .env file in the root directory of your project. Add environment-specific variables on new lines in the form of NAME=VALUE. For example:

    DB_HOST=localhost DB_USER=root DB_PASS=s1mpl3

  3. Usage (process.env now has the keys and values you defined in your .env file.)

    var db = require('db') db.connect({ host: process.env.DB_HOST, username: process.env.DB_USER, password: process.env.DB_PASS })

NOTE: Make sure your .gitignore has an entry to ignore .env files.

Upvotes: 3

Cisco
Cisco

Reputation: 23042

You can use a module called dotenv which will load an environments variables defined in a .env file or any file you specify. You would then load the .env in two ways:

  1. In the main script file, call require('dotenv').config()
  2. Via npm script: "dev": "node -r dotenv/config app.js"

Either works, but you do not want to commit .env to source control. Always keep sensitive credentials out. You can create a an .env.example to alert new users the required variables.

Upvotes: 0

Related Questions