What is process.env.PORT in Node.js?

node.jsExpressPort

node.js Problem Overview


what is process.env.PORT || 3000 used for in Node.js? I saw this somewhere:

 app.set('port', process.env.PORT || 3000);

If it is used to set 3000 as the listening port, can I use this instead?

app.listen(3000);

If not why?

node.js Solutions


Solution 1 - node.js

In many environments (e.g. Heroku), and as a convention, you can set the environment variable PORT to tell your web server what port to listen on.

So process.env.PORT || 3000 means: whatever is in the environment variable PORT, or 3000 if there's nothing there.

So you pass that to app.listen, or to app.set('port', ...), and that makes your server able to accept a "what port to listen on" parameter from the environment.

If you pass 3000 hard-coded to app.listen(), you're always listening on port 3000, which might be just for you, or not, depending on your requirements and the requirements of the environment in which you're running your server.

Solution 2 - node.js

  • if you run node index.js ,Node will use 3000

  • If you run PORT=4444 node index.js, Node will use process.env.PORT which equals to 4444 in this example. Run with sudo for ports below 1024.

Solution 3 - node.js

When hosting your application on another service (like Heroku, Nodejitsu, and AWS), your host may independently configure the process.env.PORT variable for you; after all, your script runs in their environment.

Amazon's Elastic Beanstalk does this. If you try to set a static port value like 3000 instead of process.env.PORT || 3000 where 3000 is your static setting, then your application will result in a 500 gateway error because Amazon is configuring the port for you.

This is a minimal Express application that will deploy on Amazon's Elastic Beanstalk:

var express = require('express');
var app = express();

app.get('/', function (req, res) {
  res.send('Hello World!');
});

// use port 3000 unless there exists a preconfigured port
var port = process.env.PORT || 3000;

app.listen(port);

Solution 4 - node.js

In some scenarios, port can only be designated by the environment and is saved in a user environment variable. Below is how node.js apps work with it.

The process object is a global that provides information about, and control over, the current Node.js process. As a global, it is always available to Node.js applications without using require().

The process.env property returns an object containing the user environment.

An example of this object looks like:

{
  TERM: 'xterm-256color',
  SHELL: '/usr/local/bin/bash',
  USER: 'maciej',
  PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin',
  PWD: '/Users/maciej',
  EDITOR: 'vim',
  SHLVL: '1',
  HOME: '/Users/maciej',
  LOGNAME: 'maciej',
  _: '/usr/local/bin/node'
}

For example,

terminal: set a new user environment variable, not permanently

export MY_TEST_PORT=9999

app.js: read the new environment variable from node app

console.log(process.env.MY_TEST_PORT)

terminal: run the node app and get the value

$ node app.js
9999

Solution 5 - node.js

Dotenvis a zero-dependency module that loads environment variables from a .env file into process.env. Storing configuration in the environment separate from code is based on The Twelve-Factor App methodology.

with npm

npm install dotenv

or with Yarn

yarn add dotenv

Usage

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

> require('dotenv').config()

first create a .env file in file explorer and write inside it:

PORT: 8080

const http = require("http");

require("dotenv").config();

let port = process.env.PORT;
let host = process.env.HOST;

let server = http.createServer((req, res) => {
  console.log("Thanks for the request");
  res.writeHead(200, { "Content-Type": "text/plain" });
  res.end("You Rock");
});

server.listen(port, host, () => {
  console.log(`Server is listening ${host}:${port}`);
});

Solution 6 - node.js

process.env.PORT || 3000 means: process.env.PORT means the PORT number you manually set. 3000 is the default port. If you havent set it manually then it will listen to 3000.

app.set('port', process.env.PORT || 3000) or app.listen(3000) in your code means the same. It only says what port its supposed to listen as parameter from the environment.

3000 is the hard-coded parameter which you pass to app.listen(), which means whenever you run your back-end code you're always going to listening on port 3000, which might be for you or not, depending on your requirements and the requirements of the environment in which you're server is running.

Solution 7 - node.js

Click to show 2 definitions.

(property) NodeJS.Process.env: NodeJS.ProcessEnv
The process.env property returns an object containing the user environment. See environ(7).

An example of this object looks like:

{
  TERM: 'xterm-256color',
  SHELL: '/usr/local/bin/bash',
  USER: 'maciej',
  PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin',
  PWD: '/Users/maciej',
  EDITOR: 'vim',
  SHLVL: '1',
  HOME: '/Users/maciej',
  LOGNAME: 'maciej',
  _: '/usr/local/bin/node'
}
It is possible to modify this object, but such modifications will not be reflected outside the Node.js process, or (unless explicitly requested) to other Worker threads. In other words, the following example would not work:

$ node -e 'process.env.foo = "bar"' && echo $foo
While the following will:

import { env } from 'process';

env.foo = 'bar';
console.log(env.foo);
Assigning a property on process.env will implicitly convert the value to a string. This behavior is deprecated. Future versions of Node.js may throw an error when the value is not a string, number, or boolean.

import { env } from 'process';

env.test = null;
console.log(env.test);
// => 'null'
env.test = undefined;
console.log(env.test);
// => 'undefined'
Use delete to delete a property from process.env.

import { env } from 'process';

env.TEST = 1;
delete env.TEST;
console.log(env.TEST);
// => undefined
On Windows operating systems, environment variables are case-insensitive.

import { env } from 'process';

env.TEST = 1;
console.log(env.test);
// => 1
Unless explicitly specified when creating a Worker instance, each Worker thread has its own copy of process.env, based on its parent thread’s process.env, or whatever was specified as the env option to the Worker constructor. Changes to process.env will not be visible across Worker threads, and only the main thread can make changes that are visible to the operating system or to native add-ons.

@since — v0.1.27

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser-SView Question on Stackoverflow
Solution 1 - node.jsNitzan ShakedView Answer on Stackoverflow
Solution 2 - node.jsAbdennour TOUMIView Answer on Stackoverflow
Solution 3 - node.jsThisClarkView Answer on Stackoverflow
Solution 4 - node.jsthemefieldView Answer on Stackoverflow
Solution 5 - node.jsMilan Kumar BuraView Answer on Stackoverflow
Solution 6 - node.jsuser16622035View Answer on Stackoverflow
Solution 7 - node.jsuser17257574View Answer on Stackoverflow