Explain Codes LogoExplain Codes Logo

How to Set port in next.js

javascript
next-js
port-setting
command-line-flags
Nikita BarsukovbyNikita Barsukov·Feb 21, 2025
TLDR

Set the PORT environment variable to constitute a custom port for your Next.js application. To have the server running on port 3001, modify your package.json inside the scripts subsection in the following manner:

"scripts": { "start": "PORT=3001 next start" }

Alternatively, create a .env.local file at your project's root with:

PORT=3001

Through these environment variables, you can override Next.js's default settings hence enabling your app to execute on the specified port.

Command line port setting

To change the port immediately without modification of any environment files, make use of the -p flag directly on the command line.

In the scripts section of package.json you may choose a custom port to run the server in both development and production environments:

"scripts": { "dev": "next dev -p 3001", // Embrace the change, go offbeat! "start": "next start -p 3001" // Production party at port 3001, all invited! }

This method is highly practical for speedy testing and switching different ports.

Verify port in use

Before opting for a port number, always ensure it is not already in use. For this, run:

lsof -i tcp:<custom port>

In case of any output, the port is busy. You can then either choose another free port or end the conflicting process.

Configuring package manager

If you are using Yarn or NPM as your package manager, you might need to tweak the command a bit for their syntax:

// Yarn "scripts": { "dev": "yarn dev -p 3001" // Yarn into the groove! } // NPM "scripts": { "dev": "npm run dev -- -p 3001" // NPM isn't boring! }

Managing port conflicts

What to do when your desired port is engaged? Fear not! On Windows, you can end the task via the Task Manager:

Task Manager -> Processes -> [Your Node.js process] -> End task

Or, if on a Unix system, euthanize the process with:

kill $(lsof -t -i:<custom port>)

Specifying custom hostname

For remote testing across different devices, you can set a distinct hostname alongside your port using -H:

"scripts": { "dev": "next dev -H <custom hostname> -p <custom port>" // Feel at home at any hostname! }

Replace <custom hostname> with your local network's hostname.