Making your Node.js app accessible on a local network can be very beneficial when it comes to testing and debugging, and also evaluating the overall performance of your application as well.

To get started with this process, the first thing you need to do, is to ensure you have Node.js installed on your computer.

You can do this by running the following command:

> node -v

If Node.js is installed properly, you will receive a response indicating the current version of Node.js running in your environment.

Something like this:

v18.16.1

Having confirmed your Node.js installation, we can now proceed.

Supposing we want to make the following “Hello World” Node.js application accessible on a local network:

const http = require("http");

const hostname = "127.0.0.1";
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader("Content-Type", "text/plain");
  res.end("Hello World");
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

All we need to do, is to change the hostname in the code above, to the IP address of your computer.

Update the Hostname

To find the IP address of your computer, you can go to command prompt (for windows) and enter the following command:

> ipconfig

When you enter this command, you’re going to have some messages as response. The only thing you need to look for, is the line that says “IPv4 Address”. Copy the value of the IPv4 Address and replace the hostname variable in the code with it.

So now, your code should be looking like this:

const http = require("http");

const hostname = "YOUR_IPV4_ADDRESS";
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader("Content-Type", "text/plain");
  res.end("Hello World");
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

Where “YOUR_IPV4_ADDRESS” is the value of the IPv4 address you copied from your command prompt. Example, 192.168.0.3

So now the only thing left to do is to ensure that all the devices you want to access the application from, are connected to the same local network.

Testing the Application

You can now go on one of the devices on your local network and enter the following address in the web browser:

http://your.network.ip.address:port/

Where “your.network.ip.address” is the value of the IPv4 address you copied from your command prompt.

Note: If you’re having any trouble, check to ensure that your computer’s firewall allows incoming traffic on the specific port that your app is listening on.