Home / Node.js / Lesson 6

Ports, env vars and errors

Intermediate 6 min read Lesson 6 of 6

Hard-coding 3000 fails when the host assigns a port. Read it from the environment:

const port = process.env.PORT || 3000;
app.listen(port);

API keys and database passwords belong in environment variables or a local .env file that is gitignored. Never put them in GitHub. The dotenv package can load .env in development; many hosts inject env vars in the dashboard instead.

Add an error-handling middleware with four arguments — Express detects it by arity:

app.use((err, req, res, next) => {
  console.error(err);
  res.status(500).json({ error: 'Server error' });
});

Do not send stack traces to the client in production.