A workaround using environment variables via .env file
Thanks to this github comment
For development
- Create a script for your dev environment in the project root e.g.
dev-server.js
// dev-server.js
require('dotenv').config(); // require dotenv
const cli = require('next/dist/cli/next-dev');
cli.nextDev(['-p', process.env.PORT || 3000]);
Then you can set a custom port in your .env like this: PORT=3002
Update the dev command in your package.json to use the dev-server.js script like this:
"scripts": {
"dev": "node dev-server.js"
}
- Run
npm run dev and the NextJS application will start on port 3002.
For production
- Create a script for your prod environment in the project root e.g.
prod-server.js
// prod-server.js
require('dotenv').config(); // require dotenv
const cli = require('next/dist/cli/next-start');
cli.nextStart(['-p', process.env.PORT || 3000]);
Then you can set a custom port in your .env like this: PORT=3002
Update the start command in your package.json to use the prod-server.js script like this:
"scripts": {
"build": "next build",
"start": "node prod-server.js"
}
- Run
npm run start and the NextJS application will start on port 3002. (Don't forget to build the project before with npm run build)
dotenv should be installed via npm install dotenv, required and configured in the scripts as seen in the code snippets before.
Note from the github comment:
There are some hosting providers that just force us to have server.js/index.js file. The bonus of the above solution is that it doesn't require any additional dependency.