DEV Community

Cover image for Deploying Next.js to Your Local IP Address with Dynamic Port Assignment for Network Access
Alexander Selorm Kubi
Alexander Selorm Kubi

Posted on • Edited on

Deploying Next.js to Your Local IP Address with Dynamic Port Assignment for Network Access

Ever tried to start your JS/TS development server and wanted to access your dev server from another device but didn't know how? Well, here's a solution!

This short tutorial will show you how to dynamically find an available port, display the network IP, and allow access to your server from different devices on your network. Let's get started!

Step 1: Install the Required Package

First, we need a magical tool to help us out. Meet get-port — your new best friend in port management 😃.

yarn add get-port
or
npm install get-port
Enter fullscreen mode Exit fullscreen mode

Step 2: Create a Script to Find Available Ports

Next, we’ll create a script that finds an available port and displays the network IP address.

Create start-dev.mjs file

Create a file named start-dev.mjs with the following content:

import { execSync } from 'child_process';
import getPort from 'get-port';

(async () => {
  try {
    // Get the network IP address of the machine
    const ip = execSync('ipconfig getifaddr en0').toString().trim();

    // Function to find an available port within a range
    const getAvailablePort = async (start, end) => {
      const portsInUse = [];
      for (let port = start; port <= end; port++) {
        try {
          const availablePort = await getPort({ port });
          if (availablePort === port) {
            return { port, portsInUse };
          } else {
portsInUse.push(port);
}
        } catch (error) {
         console.log(error)
        }
      }
      throw new Error(`No available ports found in range ${start}-${end}`);
    };

    // Get an available port in the range 3000-3100
    const { port, portsInUse } = await getAvailablePort(3000, 3100);

    if (portsInUse.length > 0) {
      console.log(`🚧 Ports in use: ${portsInUse.join(', ')}`);
    }
    console.log(`Starting server at http://${ip}:${port}`);

    // Set environment variables
    process.env.HOST = ip;
    process.env.PORT = port;

    // Start the Next.js development server
    execSync(`next dev -H ${ip} -p ${port}`, { stdio: 'inherit', env: { ...process.env, HOST: ip, PORT: port } });
  } catch (error) {
    console.error('Failed to start development server:', error.message);
  }
})();
Enter fullscreen mode Exit fullscreen mode

Step 3: Update Your package.json

Now, let's update your package.json to use the new script.

Modify package.json

Add the following script to your package.json:

{
  "scripts": {
    "dev": "node --experimental-modules start-dev.mjs"
  }
}
Enter fullscreen mode Exit fullscreen mode

Explanation of the Scripts

  • start-dev.mjs Script: This script handles finding an available port, setting the necessary environment variables, and starting the Next.js development server.

Step 4: Running Your Development Server

Now, fire up your terminal and run:

yarn dev 
or
npm run dev
Enter fullscreen mode Exit fullscreen mode

What Happens When You Run yarn dev or npm run dev?

  1. Finding the IP Address: The script retrieves your machine's IP address with the ipconfig getifaddr en0 command.
  2. Checking for Available Ports: The script checks for available ports within the range 3000-3100.
  3. Displaying Ports in Use: If any ports are already taken, the script logs them to the console.
  4. Setting Environment Variables: The script sets the HOST and PORT environment variables for the development server.
  5. Starting the Server: The script starts the development server on the available port and logs the network IP and port to the console.

Accessing the Server from Other Devices

Once the server is running, you can access it from other devices on the same network using the network IP and port displayed in the console. For example, if the console logs:

Starting server at http://192.168.1.10:3001
Enter fullscreen mode Exit fullscreen mode

You can access the server from another device on the same network by entering http://192.168.1.10:3001 in your browser's address bar.

Conclusion

With this setup, you'll be able to access your development server from any device on your network. This makes it easy to test your application on multiple devices.

Happy coding! 🧙‍♂️✨

Top comments (0)