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.

JavaScript
'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:

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.

Similar Reads

Prerequisites

Next.jsReactJSJavaScript...

Steps to Create the Next App

Step 1: Create a NextJS application using the following command...

Method 1: 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....

Method 2: Using command-line

In this approach, we define the port number when launching the Next.js development server via the command npm run dev — -p . This will starts the server on specified port number instead of the default port 3000....