Home > Net >  Why use a static port for express in dev environment but not in production?
Why use a static port for express in dev environment but not in production?

Time:01-05

Been looking around and multiple sources (i.e tutorials and examples) state that you start a server like this:

const port = process.env.PORT || 5000;
app.listen(port, () => {
  console.log(`Server is listening on port ${port}`);
});

But when deploying you write like this below: (which is also stated by the deploy service "Setup Node.js App" which seems to be a common tool)

app.listen();

Naturally, I'd use something like below to combat this issue:

if (process.env.NODE_ENV == "prod") {
  app.listen(0, () => {
    console.log("prod");
  });
} else {
  app.listen(process.env.PORT, () => {
    console.log(`Server is listening on port ${port}`);
  });
}

But when testing the 'prod' environment on localhost the script compiles well but I get ECONNREFUSED in Postman. Why do I need to setup a port while on dev but I'm supposed to not set anything static in production? My own analysis on that is because of a best-practice method but since the deployment tool also warns about it and using no parameters in listen() fails - I get a bit unsure of why people are doing this.

CodePudding user response:

When you are developing, a static port is nice because you always know where to reach it on your local machine. The only thing is that the port you specify must not be taken already.

When publishing to a cloud provider, you don't know what port the is should run on. Either the server lets Express choose it's own, or chooses a port that suits him best.

If you want to reach the prod version via Postman, you have to know the port chosen by Express. You can get it like this:

let server = app.listen(0, () => {
  console.log(`Example app listening on port`, server.address().port);
});
  • Related