When working with Next.js, your development server usually runs on port 3000 by default. But what if that port is already in use, or you just want to run your app on a different port — say 4000 or 8080? Setting a custom port in Next.js is simple, and there are multiple ways to do it depending on your setup. Here’s how you can configure it properly.
How to Set Port in NextJs?
Step 1: Run Next.js with a Custom Port using CLI
The quickest way is by passing the -p flag when starting your app:
npm run dev -- -p 4000
or if you’re using yarn:
yarn dev -p 4000
This will start your development server on http://localhost:4000.
Step 2: Use Environment Variables
You can also define the port through an environment variable, which is especially useful for production or containerized environments.
Create or edit a .env.local file in your project root:
PORT=4000
Then run your app normally:
npm run dev
Next.js automatically picks up the PORT variable and runs on that port.
Step 3: Modify the package.json Script
If you want your project to always start on a specific port, modify your package.json like this:
{
"scripts": {
"dev": "next dev -p 4000",
"build": "next build",
"start": "next start -p 4000"
}
}
Now you don’t need to specify the port manually each time you start your app.
Step 4: Setting Port for Production (next start)
When running your production build using next start, you can also specify the port:
npm run build
npm run start -- -p 8080
Or define it as an environment variable:
PORT=8080 npm start
Step 5: Setting Port in Docker or CI/CD Environment
In Docker or cloud deployments (like Vercel alternatives or custom servers), the port is often defined in the environment configuration.
For example, in a Dockerfile:
EXPOSE 4000
ENV PORT=4000
CMD ["npm", "start"]
This ensures that your container listens on the specified port consistently.
Changing the port in Next.js can be done in several ways — via CLI, environment variables, package.json, or Docker configuration. For quick development, the -p flag works best. But for stable deployments, defining it in your environment variables or Docker setup is the most reliable method. Always choose the approach that best fits your environment and workflow.