Assigning a Random Port in Node

Aug 26, 2019 min read

Sometimes you want to randomly assign a port to a NodeJS/Express process instead of a hardcoded port.

To randomly assign a port in Node simply listen on port '0'.

const express = require('express');

const app = express();

// Listen on random port
------
const server = app.listen(0, ()=>{
  console.log(`Server listening on port: ${server.address().port}`); // Server listening on port 59813
});