Table of Contents
By default, a Next.js app runs on port 3000, but sometimes you need to change it—whether to avoid conflicts, run multiple apps, or meet deployment requirements
Step 1: Understand the Default Port Behavior in Next.js
Next.js uses port 3000 by default when running in development or production mode, but this can be overridden using command-line flags or by modifying the package.json file
npx next dev
npx next start
Step 2: Change the Development Port via package.json
To change the port permanently for development, edit the dev script in your package.json file and specify a new port using the -p flag
"scripts": {
"dev": "next dev -p 4000"
}
Then run your app as usual:
npm run dev
Step 3: Change the Production Port via package.json
For production, you need to build the app and then start it on a custom port by modifying the start script.
"scripts": {
"start": "next start -p 4000"
}
Then build and start your app:
npm run build && npm start
Step 4: Use Command Line to Change Port Temporarily
If you don’t want to modify package.json, you can specify the port directly in the terminal when starting the app.
For development:
npx next dev -p 5000
For production:
npx next start -p 5000
Step 5: Use Environment Variables
You can also define a custom port using environment variables, which is useful in CI/CD pipelines or Docker setups.
Create a .env.local file
PORT=6000
Then run the app using:
npm run dev