How to Set Port in NextJs?
Last Updated :
01 Aug, 2024
Setting a custom port in Next.js is essential when you want to run your development or production server on a port other than the default (3000). While Next.js doesn't directly support port configuration via .env.local for development, you can control the port using alternative methods. This article will guide you through the process of setting the port in Next.js in detail.
Prerequisites
To set the custom port in next.js we can use the following approaches:
Steps to Create the Next App
Step 1: Create a NextJS application using the following command
npx create-next-app my-pp
Step 2: Navigate to project directory
cd my-app
Project Structure:
.png)
The updated dependencies in package.json file will look like:
"dependencies": {
"next": "14.1.3",
"react": "^18",
"react-dom": "^18"
}
Method 1: Using package.json
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:
OutputMethod 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 <port_number>. This will starts the server on specified port number instead of the default port 3000.
Example: Implementation to set the PORT with the command.
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 Specifying
Port Number with command
</h3>
<button onClick={handleButtonClick}>
Show Port Number
</button>
{port && <p>Current Port: {port}</p>}
</>
);
}
Output: Run the below command to see the result.
npm run dev -- -p <port_number>
OutputConclusion
To set a custom port in Next.js, modify the start
script in package.json
or use the command-line. Both methods allow you to specify which port the development or production server should use.