NodeJS: How is the value for process.env.PORT assigned? - javascript

When I run my NodeJS app the process.env.PORT is undefined. I am noticing this when I try to log the value:
console.log(process.env.PORT) // undefined
My question is, how to I change that environment object value? Thanks for an answer!

The process.env.PORT variable returns the value of the PORT environment variable.
If for example app.js is your apps entry point, then accessing process.env.PORT from within your app would yield a value of 8080 if you were to run this on the terminal:
PORT=8080 node app.js
Update
To specify the PORT environment variable when running your app on Heroku, login to your Heroku account, select your application from the list, click the "settings" tab and then click "Reveal Config Vars". Enter a PORT key with the required port value, and click the "Add" button.

For getting your process.env.PORT you need to defined PORT varable in .env file defined at root level of project.
Then, you need to use dotenv npm package for loading process.env variables in your project.
For details about dotenv you can refer to following documentation:
https://github.com/motdotla/dotenv#readme

Related

Unable to connect to MongoDB upon deployment / production

My mongoDB connects just fine locally, then once I deploy to heroku, the connection URL becomes undefined. I have a .env file in my root directory, and a .gitignore which includes the .env. I need the mongo url to stay private, but I can only assume that this is why it shows as undefined in production...
Heres the error:
"MongooseError: The uri parameter to openUri() must be a string, got "undefined". Make sure the first parameter to mongoose.connect() or mongoose.createConnection() is a string."
Heres my require:
require("dotenv").config()
var url = process.env.MONGODB_URI
Heres my connection:
mongoose.connect(url, {
useNewUrlParser: true,
useUnifiedTopology: true
}).catch(e => {
console.error(e.message)
})
Thanks in advance for the help.
Two things you need to do, Make that .env available for the production code, It can't access your local .env file.
Second is your mongo running on production ? mean availabe and accessible for the app through 27017 port ?
don't say it is running on your local machine.
You need to setup your variables where your app is deployed. It is not accessible from your .env file that you used while developing on your local host. If you deployed to heroku - here is a documentation of what to do. If it's not deployed to heroku, you can get an idea what to do next to make it work.

How to get access to docker ENV variables in nodeJS application

I'm using this Dockerfile:
FROM node:8.4.0
COPY . /
ENV MONGO_URL=mongodb://mongo-container/data
ENV PORT=80
EXPOSE 80
CMD node /index.js
In the index.js file I want to check for the ENV variables. As the docker image is used in productive, I would run the app with development environment if the ENV variable is not set.
Something similar to this:
index.js
const mongoUrl = ENV.MONGO_URL || 'mongodb://localhost:3001'
Running the Docker image should use the productive mongoDB, running locally should use localhost DB
process.env object contains all the user environment variables. Check link for more info https://nodejs.org/api/process.html#process_process_env

How to set port for express server dynamically?

This is the question mostly asked by the beginners, as I had this question when I was starting out
How to set port for express without needing to hardcode or even choose port yourself? This is the question I had when I was starting out in node and express (I am still a beginner, have lots of things to learn). Things I wanted know other than that included,
What is difference between using app.set('port', portNum) and directly using port number in app.listen(portNum)?
How to set port for express without needing to hardcode or even choose port yourself?
###Option 1: Environment variable (recommended)
Often times you will deploy your app to a hosting provider like Heroku. Depending on how the host is configured, the system will dynamically set an environment variable and your app will need to get the port from this variable. For example, the hosting provider might run a command like this when it runs your app:
$ PORT=1234 npm start
... and within your code, you can access this variable like this:
const port = process.env.PORT;
app.listen(port);
Pro tip: Most hosting providers let you define custom environment variables too. You can test this locally by creating arbitrary variables like this:
$ FOO=bar ADMIN_EMAIL=joe#example.com npm start
...and access those variables from code like this:
const foo = process.env.FOO; //-> "bar"
const adminEmail = process.env.ADMIN_EMAIL; //-> "joe#example.com"
Option 2 - environment-specific config files (also highly recommended)
Using a config library like config and/or dotenv allows you to easily manage environment-specific config options. Your folder structure would look like this (note the names of the files):
|- config
|- default.json
|- testing.json
|- production.json
|- src
|- app.js
You then define your "default" variables and environment-specific variables:
default.json
{
"port": "3030",
"adminEmail": "dev#example.com"
}
testing.json
{
"port": "5555"
}
production.json
{
"adminEmail": "admin#example.com"
}
The config library will always use the default variables. When you are on testing it will use the default admin email and a different port. When you are on production it will use the default port but a different admin email. The way you define your "node environment" is like this (notice we use the same name as the JSON config files):
$ NODE_ENV=testing npm start
$ NODE_ENV=production npm start
Pro tip: Your configuration files can reference environment variables too! Continuing with our example from Option 1 above, you can define your production config like this:
production.json
{
"port": "PORT"
}
The config library will look for any environment variables named "PORT" and will use that value. Putting it all together, your final command to run your app might look like this:
$ NODE_ENV=production PORT=47861 npm start
Pro tip: - dotenv can be used alongside the config library for ultimate environment variable management!!
2. What is the difference between using app.set('port', portNum) and directly using port number in app.listen(portNum)?
Express allows you to set application variables using app.set - but this is just a fancy way for defining variables. You can later get the values for these variables using app.get.
Sooner or later, you are going to need to tell your app to listen for traffic on a specific port. You could do something like this:
const app = express();
app.set('port', process.env.PORT);
app.use((req, res) => { ... });
app.listen(app.get('port'));
Answers that I found to my questions
1. How to set port dynamically?
I found out that you can use number 0 in app.listen() to let express select the port randomly, then I soon found out that I now had a problem I didn't know which port to access to know if my server was running or not. So simple answer to that was to output the app.address().port in console
so a Simple express server will look like this
let http = require('http');
let express = require('express');
let app = express();
app.use('/', serveStatic('./public'));
app.get('/', (req, res) => {res.render('index')});
let server = http.createServer(app);
server.listen(0, () => {
console.log(server.address().port)
})
2. What is difference between using app.set('port', 1234) and directly using port number in app.listen(1234)?
In my experience/knowledge (honestly speaking its almost equivalent to zero) I came to believe that, app.set() sets the property in app.locals and allows retrieving of that information later (which is somewhat similar to creating a variable), but I recently read that app.set() allows the value stored to be used in you template engine and other places, which makes it quite different.
What is the difference between setting a property on app.locals and calling app.set()?
Unix [1]:
$ PORT=1234 node app.js
More permanently (for a login session) [2]:
$ export PORT=1234
$ node app.js
In Windows:
set PORT=1234
In Windows PowerShell:
$env:PORT = 1234
[1] Process-lived, while the parent process that initiates is still running. If you close terminal, variable dies.
[2] Close terminal, open a new one, variable still alive.
config.js
let config = {};
// PORTS
config.port = {};
config.port.alpha = 4050; // Server 1
config.port.beta = 4051; // Server 2
.....
module.exports = config;
app.js
const express = require("express"),
config = require("./config");
....
app.set('port',config.port[process.env.SERVER_NAME]);
app.listen(app.get('port'),function(){
console.log("Server running at "+app.get('port'));
});
Starting server
SERVER_NAME=alpha node app.js
SERVER_NAME=beta node app.js

Heroku process.env.port is undefined

I am trying to run a node.js app on heroku. I got it working local, but when i deploy it on heroku i get the following error:
Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch
This is the port i try to listen to:
const PORT = process.env.port || 3000;
When i logged what the process.env.port was it said process.env.port was undefined.
Is there anything i need to do to automatically set the port?
Edit (FIX):
So i found out where the problem was. The javascript was being minified, but the process.env.port was minified to something that didn't work. Thanks for the help.
for any one get to that post.
first check if you are writing process.env.PORT correctly.
I was writing .Port and it took 4 hours of my life to figure out the error
I had the same issue and found the solution to pass heroku dyno port variable to node start script.
If you have created a Procfile in your root directory of your project just open it.
If you haven't created a Procfile just go to root directory of your project and create a file called "Procfile". The file has no extension and it helps to heroku get the starter point of your application. More details about it: The Procfile
In Node.JS Heroku documentation there isn't provided any example how should look like Procfile.
In my case, I'm using Typescript and my output directory of .js files is in /build directory in my project folder. and I'm assuming that you have the same situation. If not, just put your starter file's directory.
Procfile:
web: PORT=$PORT node ./build/index.js
You should pass config args before run the server on heroku. In terminal type
$ heroku config:set PORT=3333
then you'll be able to get port number like this
const PORT = process.env.PORT || 3000;
If you assigned from terminal
console.log(PORT) => 3333
otherwise
console.log(PORT) => 3000
If you're using babel, do not use the babel plugin babel-plugin-transform-inline-environment-variables in Heroku.
I think Heroku does not set the PORT variable when doing a deployment, so that's why you would get undefined.
Just wanted to leave this for anybody who was confused like me, you have to use
process.env.PORT
NOT
process.env.$PORT

MongoDB disabled by default [duplicate]

I have to meteor application in local (admin and client). Applications run on different port 3000 and 3003. I want to use both app should use the same DB. export MONGO_URL=mobgodb://127.0.0.1:3001/meteor will be okay. But I would like to know any argument to pass with meteor command to setup environment variable to use the same DB.
If you are looking for a start script you could do the following:
In the root of your app, create a file called start.sh:
#!/usr/bin/env bash
MONGO_URL=mobgodb://127.0.0.1:3001/meteor meteor --port 3000
Then run chmod +x start.sh
You can then start your app just by typing ./start.sh

Categories