I’m working on a project where I need to run an npm script with extra environment variables, but I can’t modify the package.json file. My current setup has a script called “build” defined like this:
"build": "cross-env NODE_ENV=production node app"
I want to pass additional variables when running the script, something like:
npm run build CUSTOM_PORT=3000
Basically I need the equivalent of running:
npm run cross-env NODE_ENV=production CUSTOM_PORT=3000 node app
But since I can’t change the package.json, is there a way to achieve this? I’ve looked through documentation but haven’t found a clear solution for passing extra environment variables to existing npm scripts.
You can prefix your npm command with the environment variables directly in the shell. Instead of trying to pass them as arguments to npm run, set them before the command:
CUSTOM_PORT=3000 npm run build
This works because environment variables set this way are inherited by the child process (your npm script). The cross-env in your build script will see both NODE_ENV=production (from package.json) and CUSTOM_PORT=3000 (from your command line).
On Windows, you’d need to use set command or install cross-env globally, but the Unix-style approach above works on most systems. I’ve used this method extensively in CI/CD pipelines where modifying package.json isn’t practical. The variables become available in your Node.js app through process.env.CUSTOM_PORT.
just use the --
syntax to pass env vars through npm. try npm run build -- CUSTOM_PORT=3000
and it should work. i think this passes everything after the double dash directly to your script command.
Another approach that’s worked well for me is using dotenv-cli as an alternative. You can install it globally with npm install -g dotenv-cli
and then run your scripts like dotenv -e .env.local npm run build
where you create temporary environment files for different scenarios. However, the simplest solution I’ve found is actually using npm’s built-in environment variable passing. You can export variables in your current shell session before running the script: export CUSTOM_PORT=3000
then npm run build
. This is particularly useful when you need to run multiple commands with the same environment setup. I’ve also had success creating wrapper shell scripts in projects where this pattern is common. Just create a build.sh file that sets your variables and calls the npm script. This keeps things organized without touching package.json and makes it easier for team members to understand the different build configurations available.