Sudhir S Pawar
Sudhir S Pawar

Reputation: 65

unable to use .env variables in express js

I am new to node and express js facing issue to access .env variables webapp.js:

const express = require("express");
const app = express();
require('dotenv').config();

app.listen(process.env.app_port, () => { 
//console.log("server running....", process.env);
console.log("server running....", process.env.app_port);
});

.env file:

node_env : development
app_port : 5000
db_port : 3306
host : localhost
user : root
password : 
database : job_portal
connectionLimit : 10

package.json

{
  "name": "webservices",
  "version": "1.0.0",
  "main": "webapp.js",
  "scripts": {
    "start": "nodemon webapp.js",
    "dev": "nodemon webapp.js"    
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "bcrypt": "^5.0.0",
    "express": "^4.17.1",
    "mysql": "^2.18.1"
  },
  "devDependencies": {
    "cross-env": "^7.0.2",
    "dotenv": "^8.2.0",
    "nodemon": "^2.0.4"
  },
  "description": ""
}

I am trying to access variable in webapp.js from .env file but it return undefined how to fix this?

Upvotes: 2

Views: 1712

Answers (2)

Automaton Angle
Automaton Angle

Reputation: 11

   #YOU VARIABLES SHOULD CAPITALISE AS THIS IS THE CONVENTION
    NODE_ENV=development
    APP_PORT=5000
    DB_PORT=3306
    HOST=localhost
    USER=root

Upvotes: 1

Som
Som

Reputation: 144

change your.env file to

node_env = development
app_port = 5000
db_port = 3306
host = localhost
user = root

Upvotes: 2

Related Questions