Ever tried to start your Next.js development server and wanted to access your dev server from another device but didn't know how? Say goodbye to those issues and hello to smooth, network-wide access! In this tutorial, we’ll 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
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
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);
}
})();
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"
}
}
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
What Happens When You Run yarn dev
-
Finding the IP Address: The script retrieves your machine's IP address with the
ipconfig getifaddr en0
command. - Checking for Available Ports: The script checks for available ports within the range 3000-3100.
- Displaying Ports in Use: If any ports are already taken, the script logs them to the console.
-
Setting Environment Variables: The script sets the
HOST
andPORT
environment variables for the Next.js server. - Starting the Server: The script starts the Next.js 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
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, your Next.js development server will always find a nice, available port to work on, and you'll know exactly which ports were already in use. Plus, you'll be able to access your development server from any device on your network. This makes for a happier, conflict-free development experience and makes it easy to test your application on multiple devices.
So, what are you waiting for? Get started and keep your Next.js server hopping along on the perfect port every time, accessible from all your network devices. Happy coding! 🧙♂️✨
Top comments (0)