node.jsexpressport

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


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?


Solution

  • 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.