By modifying package.json file
In this approach we will modify the package.json. Here we modify the script section by adding “dev”: “next dev -p 4000“. This will starts the server on port 4000 instead of the default port 3000.
Below is the modified script section:
"scripts": {
"build": "next build",
"start": "next start",
"lint": "next lint",
"dev": "next dev -p 4000"
}
Example: Implementation to set the PORT by changing in the package.josn file.
'use client';
import { useState } from 'react';
export default function Home() {
const [port, setPort] = useState(null);
const handleButtonClick = () => {
// Get the port number
const currentPort = window.location.port;
setPort(currentPort);
};
return (
<>
<h3>
Setting Port Number By
Modifying package.json
</h3>
<button onClick={handleButtonClick}>
Show Port Number
</button>
{port && <p>Current Port: {port}</p>}
</>
);
}
Output:
How to Set Port in NextJs?
Next.js, a popular React framework, offers a seamless development experience with many built-in features. One of the common tasks when working with Next.js is setting the port for your application. By default, Next.js applications run on port 3000. However, you might want to change this for various reasons, such as avoiding port conflicts or following specific project requirements. This article will guide you through the process of setting the port in Next.js in detail.