I have a .env
file in my root directory that has PORT=4000
inside
My app.js
has the following code
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
require('dotenv').config();
app.get('/', (req, res) => {
res.send('Hello World!!!');
console.log(port);
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
But when I run the app with nodemon app.js
, the port
is 3000 instead of 4000. Why is my .env
PORT
variable undefined?
This code solves the issue
require('dotenv').config();
const express = require('express');
const app = express();
const port = process.env.PORT;
app.get('/', (req, res) => {
res.send('Hello World!!!');
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});