Assigning a Random Port in Node

08-26-2019


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

1
2
3
4
5
6
7
8
9
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
});