
Next.js Custom port from env
January 23, 2025
1 min read
portfolio
dotenv
next.js
How to Customize the Default Port in Next.js
By default, a Next.js application runs on port 3000
. If you want to change the default port to a custom one, follow these methods:
1. Using Environment Variables
You can specify the port directly in the command line when starting the Next.js server:
shell
PORT=4000 next dev
Alternatively, add it to your .env.local
file:
plain text
PORT=4000
Then start your application as usual:
shell
next dev
2. Using a Custom Script in package.json
Modify the scripts
section in package.json
to include the desired port:
json
"scripts": {
"dev": "next dev -p 4000"
}
Now, run the command:
shell
npm run dev
3. Using a next.config.js
File (Alternative Approach)
You can programmatically control the port in next.config.js
:
javascript
module.exports = {
devIndicators: {
autoPrerender: false,
},
env: {
PORT: 4000,
},
};
This method ensures the port is set within the Next.js configuration.
Conclusion
Customizing the Next.js default port is simple and can be done in multiple ways depending on your workflow. Choose the method that best suits your project setup. 🚀