Updating package.json File
In this approach, we are updating the “scripts” section in package.json to specify the desired port, such as “dev”: “next dev -p 3001“. This configures Next.js to run on the specified port when using the development script, allowing the React component to detect and display the current port when a button is clicked.
Syntax:
"dev": "next dev -p "port_Number",
Update the “scripts” section in package.json to specify the desired port:
{
"scripts": {
"dev": "next dev -p 3001",
"build": "next build",
"start": "next start"
}
}
Example: The below example is displayed on the port number which is updated in package.json file.
//src/app/page.js
'use client';
import React from 'react';
const Page = () => {
const handleButtonClick = () => {
const currentPort = window.location.port || 3000; // Default port if not specified
alert(`The current port is: ${currentPort}`);
};
return (
<div>
<h1>Approach 1: Updating package.json File</h1>
<button onClick={handleButtonClick}>Show Current Port</button>
</div>
);
};
export default Page;
Step to run the application: Now run the application with the below command:
npm run dev
Output:
How to change port in Next.js App
Next.js provides the flexibility to change the default port of the development server using command-line options such as -p <port_number> or by updating the “scripts” section in the package.json file, offering developers multiple ways to customize the port configuration based on their requirements.
Table of Content
- 1. Updating package.json File
- 2. Specify Port Number in Run Command