243

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?

ThisClark
  • 14,352
  • 10
  • 69
  • 100
user-S
  • 3,019
  • 3
  • 16
  • 10

7 Answers7

317

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.

Nitzan Shaked
  • 13,460
  • 5
  • 45
  • 54
  • Good to have Heroku mentioned here. Can I use this for the ip address as well as I do not want to expose the standard localhost 127.0.0.1 but the ip from the router perspective so that my other pcs can reach my app, e.g. '192.168.0.3' – Timo Feb 20 '22 at 17:01
101
  • 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.

Dan
  • 506
  • 5
  • 18
Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254
54

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);
Ashok Arora
  • 531
  • 1
  • 6
  • 17
ThisClark
  • 14,352
  • 10
  • 69
  • 100
  • 3
    Within Node.js supporting ES6 you can write even shorter: `const {PORT = 3000} = process.env` – Julian Mar 18 '18 at 09:12
  • 1
    @PA. no PA, if process.env.port is found on the production environnement so port will get the value of it. Remember that this operation will be read from left to right and stop at the first available value if any. – HoCo_ May 13 '18 at 22:09
  • If we want to route to specific url without specifying the port after, how do we do this? – Wolfy Feb 17 '23 at 04:34
  • I think this deserves its own post and may have already been asked/answered, but I'll take a shot at it for you. It depends how much access you have to manage the backend. Is it load balanced? Behind a proxy? Are you using redirection? It may be possible to redirect ports 80 or 443 to port 3000 for example using iptables. From the user perspective they are connecting to the default protocol port for http or https and internally you are redirecting them to the port your server is hosted on. That is the idea anyway. It comes down to configuration. Consider this: https://serverfault.com/a/1019123 – ThisClark Feb 17 '23 at 17:24
13

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
themefield
  • 3,847
  • 30
  • 32
4

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}`);
});
Milan Kumar Bura
  • 350
  • 5
  • 11
1
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
  • 2
    Please edit your answer using: https://stackoverflow.com/editing-help if some text is not part of the code. – m4n0 Oct 27 '21 at 06:58
0

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.