Using .env file to specify server listening port of the Next.js server

I've been searching for a method how to set up the server port of the Next.js application. I found 2 methods:

  1. Hardcoding into the package.json file:

    { "scripts": { "dev": "next dev -p 8012", "build": "next build", "start": "next start -p 8012", } }

  2. From the command line: npm run dev -- -p 8012 OR PORT=8012 npm run dev

None of these looks fine to me. The problem with the first approach is that package.json is versioned by git. This means that I must use the same port on my local env as is used on production. I may have some other program listening on that port locally. This is inconvenient to me.

The second approach implies that my memory serves me very well. I have to memorize the port I want to use locally as well as on production, staging or any other environemnt. This is not OK too.

Ideally, I would like to have the PORT specified in the .env files. I tried it - doesn't work.

Have anyone come across such an issue?


Solution 1:

Next.js doesn't currently support using the PORT environment variable inside a .env file (See discussion).

The two options that could work for your use case would be:

  1. Exporting $PORT in your environment. But it has drawbacks, as pointed out in the linked discussion.
# In your shell
export PORT=8012
// package.json
"scripts": {
    "start": "next start --port ${PORT-3000}",
},
  1. Creating a custom start script to read the port from your .env file.
//server.js
const cli = require('next/dist/cli/next-start');
cli.nextStart(['-p', process.env.PORT || 3000]);
//package.json
{
  "scripts": {
    "start": "node server.js",
  }
}