Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

next.js

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?

like image 237
Hairi Avatar asked Jan 21 '26 04:01

Hairi


1 Answers

An easy way to read the port from .env file is to use dotenv-cli package:

  1. Install the package: npm install dotenv-cli
  2. Use the following start script to read PORT env variable from .env and .env.local files (omit -c flag to only read .env file):
"start": "dotenv -c -- next start",
like image 107
Samuli Asmala Avatar answered Jan 27 '26 01:01

Samuli Asmala