How to Set port in next.js
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:
Alternatively, create a .env.local
file at your project's root with:
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:
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:
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:
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:
Or, if on a Unix system, euthanize the process with:
Specifying custom hostname
For remote testing across different devices, you can set a distinct hostname alongside your port using -H
:
Replace <custom hostname>
with your local network's hostname.
Was this article helpful?