587

How to set some environment variables from within package.json to be used with npm start like commands?

Here's what I currently have in my package.json:

{
  ...
  "scripts": {
    "help": "tagove help",
    "start": "tagove start"
  }
  ...
}

I want to set environment variables (like NODE_ENV) in the start script while still being able to start the app with just one command, npm start.

Flip
  • 6,233
  • 7
  • 46
  • 75
dev.meghraj
  • 8,542
  • 5
  • 38
  • 76

21 Answers21

727

Set the environment variable in the script command:

...
"scripts": {
  "start": "node app.js",
  "test": "NODE_ENV=test mocha --reporter spec"
},
...

Then use process.env.NODE_ENV in your app.

Note: This is for Mac & Linux only. For Windows refer to the comments.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
cesar
  • 10,238
  • 2
  • 20
  • 17
  • 89
    Has some one figured out an alternate for windows..? – infinity Dec 03 '15 at 22:12
  • @infinity [Better npm run](https://www.npmjs.com/package/better-npm-run) solves cross-platform compatibility issues. Its config is somewhat clumsy though. – jokka Dec 18 '15 at 12:27
  • 100
    @infinity use [cross-env](https://www.npmjs.com/package/cross-env) and is very easy to use. – mikekidder Jan 30 '16 at 16:33
  • 176
    @infinity use `set NODE_ENV=test&& mocha --reporter spec` - there is no space between the test and && on purpose. – Jamie Penney Feb 22 '16 at 19:14
  • 5
    Thanks @JamiePenney. I had to remove the space before && to get it to work. Why is that? `set NODE_ENV=development&& (nexttask) – TetraDev May 20 '16 at 22:35
  • @TetraDev can't remember sorry, I think it was including the space in the set call? – Jamie Penney Jun 07 '16 at 04:16
  • 3
    cross-env worked in seconds for me. Consider only adding it with --save-dev if you just need it for npm test – Jerico Sandhorn Feb 28 '17 at 21:12
  • Doesn't work for `npm run-script build`. Error thrown *'NODE_ENV' is not recognized as an internal or external command, operable program or batch file`* – Green Apr 11 '17 at 18:19
  • 32
    `"test": "NODE_ENV=test mocha --reporter spec"` will not work on Windows systems. – Benny Code May 12 '17 at 12:11
  • @TetraDev I think you would end up with `NODE_ENV` set to 'test ' (note the space). No space is a way to avoid that in case you don't want to (or can't) use quotes. – Ivan Schwarz Jul 06 '17 at 13:40
  • 2
    If you do use cross-env there is no need to include '&&'. Example: `cross-env NODE_ENV=test karma start` – larrydalmeida Aug 12 '17 at 06:48
  • 25
    @infinity @jamie-penney `env NODE_ENV=test mocha --reporter spec` will use the declared environment variable in a natively cross platform fashion, but the key is it is used by npm in an ad hoc and one-time fashion, just for the npm script execution. (It's not set or exported for future reference.) As long as you're running your command from the npm script, there's no issue. Also, the "&&" must be removed when doing it this way. – estaples Apr 05 '18 at 16:10
  • if you want to use the env var inside the script itself you need to prepend $, for example if you run `mode=prod npm run print` and you have a script in your package.json called print `"print": "echo environment '$mode'"` it will print `environment 'prod'` – Jonathan Morales Vélez Aug 24 '18 at 10:17
  • 3
    @infinity Multiple environment variables can be set on windows like so: "scripts": { "start": "node index.js", "set:env:this:way": "env FIRST=one env SECOND=two node index.js" }, – Greg Oct 21 '19 at 16:15
  • 8
    `Note: env ensures that it works across platforms.` How? `env` is not a valid command on Windows. – Timmmm Jan 24 '20 at 15:18
  • 2
    What is the `env` you refer to here? Can you post a link? – Qwerty Jan 27 '20 at 10:43
  • on windows it works like this: scripts: { "testing": "cypress open --env CYPRESS_CypressBaseUrl=localhost:3000"} ( here: npm > 6, node > 13 ) – theRealEmu Oct 06 '20 at 12:21
  • I want to use a .env file so that I have all of those important details in a single spot, and so I can run the server from the terminal, or from docker, or docker-compose or whatever. Not finding this very helpful... – John Jun 30 '21 at 08:21
  • 1
    As a Windows users (in 2021), you can use WSL (Windows Subsystem for Linux) to run my Node projects locally. This video [https://www.youtube.com/watch?v=lOXatmtBb88](https://www.youtube.com/watch?v=lOXatmtBb88) explains how to setup VSCode to use the WSL command line instead of PowerShell. This allows you to run projects such as [https://github.com/mattcarlotta/nextjs-ssr-kit](https://github.com/mattcarlotta/nextjs-ssr-kit) from Windows. If you look at the package.json script in this example project you will see it sets environment variables within the node commands. – w. Patrick Gale Jul 06 '21 at 13:29
  • As what @w.PatrickGale has suggested, to run WSL in vscode. I believe it might be possible to simply run the `bash` command in cmd to change to a Linux environment too. – Jarrett Oct 07 '21 at 05:31
  • env-cmd is better – mercury Jun 02 '22 at 16:30
369

Just use NPM package cross-env. Super easy. Works on Windows, Linux, and all environments. Notice that you don't use && to move to the next task. You just set the env and then start the next task. Credit to @mikekidder for the suggestion in one of the comments here.

From documentation:

{
  "scripts": {
    "build": "cross-env NODE_ENV=production OTHERFLAG=myValue webpack --config build/webpack.config.js"
  }
}

Notice that if you want to set multiple global vars, you just state them in succession, followed by your command to be executed.

Ultimately, the command that is executed (using spawn) is:

webpack --config build/webpack.config.js

The NODE_ENV environment variable will be set by cross-env

RobC
  • 22,977
  • 20
  • 73
  • 80
TetraDev
  • 16,074
  • 6
  • 60
  • 61
  • 2
    Triple backslashes can be used to escape required quotes: `"test": "cross-env TS_NODE_COMPILER_OPTIONS='{\\\"module\\\":\\\"commonjs\\\"}' mocha"` – bvj Mar 08 '18 at 03:15
  • Can someone finally help me decide if I should use `env` or `cross-env`? On one hand, env doesn't require me to install anything and on the other hand `cross-env` is more popular. Can someone please confirm if `env` works on all platforms? – Rishav Apr 01 '20 at 17:38
  • 3
    @Rishav `env` does not work as-is on all platforms, hence the reason for `cross-env` to exist. Just use `cross-env` and be done with it. – TetraDev Jun 02 '20 at 23:41
  • Also, may be used cross-env-shell instead of cross-env. You can read about it here : https://www.npmjs.com/package/cross-env#cross-env-vs-cross-env-shell – Nigrimmist Nov 13 '21 at 21:44
  • 1
    It doesn't work for the `install` script though, I am struggling with Playwright to set PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 before running the install of playwright package – Eric Burel Jan 05 '22 at 07:12
  • This seems to work better for install, based on @Teemuk answer: `"preinstall": "export PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 || set PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1"` The difficulty is that during install, you have no package, and you cannot have an inline script, so you have to find a pure shell solution that works for Windows, in the `preinstall` command. – Eric Burel Jan 05 '22 at 07:24
  • This package is now deprecated. [env-cmd](https://stackoverflow.com/a/57201206/542251) is the obvious replacement – Liam Sep 06 '22 at 07:42
84

Because I often find myself working with multiple environment variables, I find it useful to keep them in a separate .env file (make sure to ignore this from your source control). Then (in Linux) prepend export $(cat .env | xargs) && in your script command before starting your app.

Example .env file:

VAR_A=Hello World
VAR_B=format the .env file like this with new vars separated by a line break

Example index.js:

console.log('Test', process.env.VAR_A, process.env.VAR_B);

Example package.json:

{
  ...
  "scripts": {
    "start": "node index.js",

    "env-linux": "export $(cat .env | xargs) && env",
    "start-linux": "export $(cat .env | xargs) && npm start",

    "env-windows": "(for /F \"tokens=*\" %i in (.env) do set %i)",
    "start-windows": "(for /F \"tokens=*\" %i in (.env) do set %i) && npm start",

  }
  ...
}

Unfortunately I can't seem to set the environment variables by calling a script from a script -- like "start-windows": "npm run env-windows && npm start" -- so there is some redundancy in the scripts.

For a test you can see the env variables by running npm run env-linux or npm run env-windows, and test that they make it into your app by running npm run start-linux or npm run start-windows.

Luke
  • 18,811
  • 16
  • 99
  • 115
  • 2
    Very good, it almost did the job for me! I'd like to add a few comments: - You cannot have empty lines in your .env file - Comments in your .env file will break your script - If multiple scripts use the same .env file, you will have to repeat that - I had to remove the space before `&&` for it to work - If you have multiple .env files, it may be a little harder to maintain Your answer inspired me to prepare this suggestion: https://stackoverflow.com/questions/25112510/how-to-set-environment-variables-from-within-package-json/61052350#61052350 – Felipe N Moura Apr 06 '20 at 03:04
  • I'm not following the env-windows script. The cmd shell won't recognize export nor the xargs. – Derek Greer Sep 23 '20 at 16:45
  • Thanks for the catch @FelipeNMoura and @DerekGreer . Not sure why I thought `export $(cat .env | xargs) && set` worked on Windows. I re-did the windows script, tested it out, and made edits to my answer. – Luke Oct 16 '20 at 14:31
  • Use `export $(cat .env | xargs)&&` instead of `export $(cat .env | xargs) &&` to avoid an extra whitespace in the env variables. These spaces won't show up in console.log and can mess up the code(as it did mine) – Parth Sindhu Oct 06 '21 at 21:34
  • 1
    This should be the accepted answer. – LUser Jan 08 '22 at 21:46
82

I just wanted to add my two cents here for future Node-explorers. On my Ubuntu 14.04 the NODE_ENV=test didn't work, I had to use export NODE_ENV=test after which NODE_ENV=test started working too, weird.

On Windows as have been said you have to use set NODE_ENV=test but for a cross-platform solution the cross-env library didn't seem to do the trick and do you really need a library to do this:

export NODE_ENV=test || set NODE_ENV=test&& yadda yadda

The vertical bars are needed as otherwise Windows would crash on the unrecognized export NODE_ENV command. I don't know about the trailing space, but just to be sure I removed them too.

peterh
  • 11,875
  • 18
  • 85
  • 108
TeemuK
  • 2,095
  • 1
  • 18
  • 17
  • 8
    Did you use `&&`? `NODE_ENV=test yadda` means "run `yadda`, setting `NODE_ENV` within `yadda`'s environment variables. `NODE_ENV=test && yadda` means "set `NODE_ENV` within the local environment, but don't export it, then run `yadda`." `NODE_ENV=test yadda` is the preferred approach. – Josh Kelley Jul 08 '16 at 15:21
  • Sorry that haven't checked my stackoverflow account in a while. But basically silly Windows didn't work using `NODE_ENV=test && npm run test` or something similar. I made a better solution using `process.env["NODE_ENV"] = "testing";` inside my testhelper.js file. – TeemuK Nov 03 '16 at 10:41
  • 9
    @TeemuK just to add my two cents too, when you run your command with `&&` you lost your environment variables, setting environment variables without export works on the current command only (which is nothing). to run the command with the env variable without exporting u do: `NODE_ENV=test npm run test`. Finally the reason it worked after you exported, is because ur variable is now available (exported) in the session, your NODE_ENV without export wasnt doing anything. – Tarek Feb 22 '17 at 01:32
  • If you want to set multiple envs at once remember that logic operators in both cmd and bash are strictly from left to right, so chains are easily achievable, and If you want to have clean output after execiting such cross env on windows you can do it like so: `export NODE_ENV=0 2>nul || set NODE_ENV=0 && export TRIAL_MODE=1 2>nul || set TRIAL_MODE=1 && echo "$NODE_ENV $TRIAL_MODE %NODE_ENV %TRIAL_MODE"` Please remember that on Windows cmd env are available after executing statement, so they are not available in one line solutions. – Mateusz Budzisz Sep 06 '22 at 08:52
42

Try this on Windows by replacing YOURENV:

  {
    ...
     "scripts": {
       "help": "set NODE_ENV=YOURENV && tagove help",
       "start": "set NODE_ENV=YOURENV && tagove start"
     }
    ...
  }
Daniel Tonon
  • 9,261
  • 5
  • 61
  • 64
Pascal Mayr
  • 529
  • 4
  • 5
19

@luke's answer was almost the one I needed! Thanks.

As the selected answer is very straightforward (and correct), but old, I would like to offer an alternative for importing variables from a .env separate file when running your scripts and fixing some limitations to Luke's answer. Try this:

::: .env file :::

# This way, you CAN use comments in your .env files
NODE_PATH="src/"

# You can also have extra/empty lines in it
SASS_PATH="node_modules:src/styles"

Then, in your package json, you will create a script that will set the variables and run it before the scripts you need them:

::: package.json :::

scripts: {
  "set-env": "export $(cat .env | grep \"^[^#;]\" |xargs)",
  "storybook": "npm run set-env && start-storybook -s public"
}

Some observations:

  • The regular expression in the grep'ed cat command will clear the comments and empty lines.

  • The && don't need to be "glued" to npm run set-env, as it would be required if you were setting the variables in the same command.

  • If you are using yarn, you may see a warning, you can either change it to yarn set-env or use npm run set-env --scripts-prepend-node-path && instead.

Different environments

Another advantage when using it is that you can have different environment variables.

scripts: {
  "set-env:production": "export $(cat .production.env | grep \"^[^#;]\" |xargs)",
  "set-env:development": "export $(cat .env | grep \"^[^#;]\" |xargs)",
}

Please, remember not to add .env files to your git repository when you have keys, passwords or sensitive/personal data in them!

Felipe N Moura
  • 1,367
  • 11
  • 13
  • The `export $(cat .env | grep \"^[^#;]\" |xargs) ` command works only if it is in the same script as my main script. This would work: `export $(cat .env | grep \"^[^#;]\" |xargs) && docker exec -it ${MY_VARIABLE}_wp sh`. But this won't: `npm run set-env && docker exec -it ${MY_VARIABLE}_wp sh`. – Quentin D Feb 10 '23 at 15:40
  • I couldn't able to run the grep command above. So I used egrep. `export $(cat .env | egrep '^[^#]' | xargs)` – Halil Kayer Jun 23 '23 at 09:40
17

UPDATE: This solution may break in npm v7 due to npm RFC 21

CAVEAT: no idea if this works with yarn


npm (and yarn) passes a lot of data from package.json into scripts as environment variables. Use npm run env to see them all. This is documented in https://docs.npmjs.com/misc/scripts#environment and is not only for "lifecycle" scripts like prepublish but also any script executed by npm run.

You can access these inside code (e.g. process.env.npm_package_config_port in JS) but they're already available to the shell running the scripts so you can also access them as $npm_... expansions in the "scripts" (unix syntax, might not work on windows?).

The "config" section seems intended for this use:

  "name": "myproject",
  ...
  "config": {
    "port": "8010"
  },
  "scripts": {
    "start": "node server.js $npm_package_config_port",
    "test": "wait-on http://localhost:$npm_package_config_port/ && node test.js http://localhost:$npm_package_config_port/"
  } 

An important quality of these "config" fields is that users can override them without modifying package.json!

$ npm run start

> myproject@0.0.0 start /home/cben/mydir
> node server.js $npm_package_config_port

Serving on localhost:8010

$ npm config set myproject:port 8020
$ git diff package.json  # no change!
$ cat ~/.npmrc
myproject:port=8020

$ npm run start

> myproject@0.0.0 start /home/cben/mydir
> node server.js $npm_package_config_port

Serving on localhost:8020

See npm config and yarn config docs.
It appears that yarn reads ~/.npmrc so npm config set affects both, but yarn config set writes to ~/.yarnrc, so only yarn will see it :-(

Beni Cherniavsky-Paskin
  • 9,483
  • 2
  • 50
  • 58
  • 4
    Note that [`$npm_package_*` variables are no longer automatically placed in the environment since NPM v7](https://github.com/npm/rfcs/issues/305), so this will probably break. – Dan Dascalescu Jan 07 '21 at 08:25
16

For a larger set of environment variables or when you want to reuse them you can use env-cmd.

As a plus, the .env file would also work with direnv.

./.env file:

# This is a comment
ENV1=THANKS
ENV2=FOR ALL
ENV3=THE FISH

./package.json:

{
  "scripts": {
    "test": "env-cmd mocha -R spec"
  }
}
KARASZI István
  • 30,900
  • 8
  • 101
  • 128
13

This will work in Windows console:

"scripts": {
  "setAndStart": "set TMP=test&& node index.js",
  "otherScriptCmd": "echo %TMP%"
}

npm run aaa

output: test

See this answer for details.

O'Dane Brissett
  • 1,284
  • 1
  • 8
  • 23
Serg
  • 6,742
  • 4
  • 36
  • 54
  • 7
    Should be `set TMP=test&& npm run bbb`. The space before `&&` will also cound as part of then `NODE_ENV` string – FisNaN Apr 27 '19 at 11:13
  • @FisNaN Shouldn't be the case if you surround it with quotes `"`. – kaiser Feb 04 '20 at 10:32
  • This work without the space before `&&`. So `"scripts": { "aaa": "set TMP=test&& npm run bbb", "bbb": "echo %TMP%" }` – O'Dane Brissett Jun 22 '20 at 20:38
  • @O'DaneBrissett I can't check this right now, feel free to edit the answer if you're sure it works in the Windows console. – Serg Jun 22 '20 at 20:43
13

When the NODE_ENV environment variable is set to 'production' all devDependencies in your package.json file will be completely ignored when running npm install. You can also enforce this with a --production flag:

npm install --production

For setting NODE_ENV you can use any of these methods

method 1: set NODE_ENV for all node apps

Windows :

set NODE_ENV=production

Linux, macOS or other unix based system :

export NODE_ENV=production

This sets NODE_ENV for current bash session thus any apps started after this statement will have NODE_ENV set to production.

method 2: set NODE_ENV for current app

NODE_ENV=production node app.js

This will set NODE_ENV for the current app only. This helps when we want to test our apps on different environments.

method 3: create .env file and use it

This uses the idea explained here. Refer this post for more detailed explanation.

Basically, you create a .env file and run some bash scripts to set them on the environment.

To avoid writing a bash script, the env-cmd package can be used to load the environment variables defined in the .env file.

env-cmd .env node app.js

method 4: Use cross-env package

This package allows environment variables to be set in one way for every platform.

After installing it with npm, you can just add it to your deployment script in package.json as follows:

"build:deploy": "cross-env NODE_ENV=production webpack"
Nigrimmist
  • 10,289
  • 4
  • 52
  • 53
kartik tyagi
  • 6,256
  • 2
  • 14
  • 31
11

For single environment variable

 "scripts": {
    "start": "set NODE_ENV=production&& node server.js"
 }

For multiple environment variables

 "scripts": {
    "start": "set NODE_ENV=production&& set PORT=8000&& node server.js"
 }
youngwolf
  • 461
  • 5
  • 4
  • 2
    Answers the question/works, but probably not the best. You may end up including API keys etc in your version control repo, assuming you're including your package.json in your repo. – Dan. Nov 01 '21 at 12:57
10

suddenly i found that actionhero is using following code, that solved my problem by just passing --NODE_ENV=production in start script command option.

if(argv['NODE_ENV'] != null){
  api.env = argv['NODE_ENV'];
} else if(process.env.NODE_ENV != null){
  api.env = process.env.NODE_ENV;
}

i would really appreciate to accept answer of someone else who know more better way to set environment variables in package.json or init script or something like, where app bootstrapped by someone else.

RobC
  • 22,977
  • 20
  • 73
  • 80
dev.meghraj
  • 8,542
  • 5
  • 38
  • 76
10

use git bash in windows. Git Bash processes commands differently than cmd.

Most Windows command prompts will choke when you set environment variables with NODE_ENV=production like that. (The exception is Bash on Windows, which uses native Bash.) Similarly, there's a difference in how windows and POSIX commands utilize environment variables. With POSIX, you use: $ENV_VAR and on windows you use %ENV_VAR%. - cross-env doc

{
  ...
  "scripts": {
    "help": "tagove help",
    "start": "env NODE_ENV=production tagove start"
  }
  ...
}

use dotenv package to declare the env variables

Shubham Shaw
  • 841
  • 1
  • 11
  • 24
6
{
  ...
  "scripts": {
    "start": "ENV NODE_ENV=production someapp --options"
  }
  ...
}
RobC
  • 22,977
  • 20
  • 73
  • 80
Cailean
  • 111
  • 3
  • 3
6

Running a node.js script from package.json with multiple environment variables:

  1. package.json file:

    "scripts": {
        "do-nothing": "set NODE_ENV=prod4 && set LOCAL_RUN=true && node ./x.js",
 },

x.js file can be as:

let env     = process.env.NODE_ENV;
let isLocal = process.env.LOCAL_RUN;

console.log("ENV"    , env);
console.log("isLocal", isLocal);
ylev
  • 2,313
  • 1
  • 23
  • 16
5

Most elegant and portable solution: package.json:

"scripts": {
    "serve": "export NODE_PRESERVE_SYMLINKS_MAIN=1 && vue-cli-service serve"
    },

Under windows create export.cmd and put it somewhere to your %PATH%:

@echo off

set %*
zdm
  • 443
  • 4
  • 9
4

If you:

  • Are currently using Windows;
  • Have git bash installed;
  • Don't want to use set ENV in your package.json which makes it only runnable for Windows dev machines;

Then you can set the script shell of node from cmd to git bash and write linux-style env setting statements in package.json for it to work on both Windows/Linux/Mac.

$ npm config set script-shell "C:\\Program Files\\git\\bin\\bash.exe"
Yuefeng Li
  • 315
  • 3
  • 7
2

Although not directly answering the question I´d like to share an idea on top of the other answers. From what I got each of these would offer some level of complexity to achieve cross platform independency.

On my scenario all I wanted, originally, to set a variable to control whether or not to secure the server with JWT authentication (for development purposes)

After reading the answers I decided simply to create 2 different files, with authentication turned on and off respectively.

  "scripts": {
    "dev": "nodemon --debug  index_auth.js",
    "devna": "nodemon --debug  index_no_auth.js",
  }

The files are simply wrappers that call the original index.js file (which I renamed to appbootstrapper.js):

//index_no_auth.js authentication turned off
const bootstrapper = require('./appbootstrapper');
bootstrapper(false);

//index_auth.js authentication turned on
const bootstrapper = require('./appbootstrapper');
bootstrapper(true);

class AppBootStrapper {

    init(useauth) {
        //real initialization
    }
}

Perhaps this can help someone else

RobC
  • 22,977
  • 20
  • 73
  • 80
1

You should not set ENV variables in package.json. actionhero uses NODE_ENV to allow you to change configuration options which are loaded from the files in ./config. Check out the redis config file, and see how NODE_ENV is uses to change database options in NODE_ENV=test

If you want to use other ENV variables to set things (perhaps the HTTP port), you still don't need to change anything in package.json. For example, if you set PORT=1234 in ENV and want to use that as the HTTP port in NODE_ENV=production, just reference that in the relevant config file, IE:

# in config/servers/web.js
exports.production = { 
  servers: {
    web: function(api){
      return {
       port: process.env.PORT
      }
    }
  }
}
Evan
  • 3,191
  • 4
  • 29
  • 25
  • great. i think you didn't read my question.. my problem is how to set NODE_ENV not what is use of it. – dev.meghraj Aug 05 '14 at 04:41
  • 1
    Perhaps an alternative way to explain this would be that NODE_ENV (and other environment variables) are part of the environment (hence the name). They are usually properties of the server you are running the application on rather than your application. You can set them manually via the command you exec, ie: `NODE_ENV=test npm start` or have them set by the shell – Evan Aug 06 '14 at 05:08
  • 3
    I disagree. using a ./config for every environment confines you to using static environments when you deploy your app. This is an outdated philosophy that will not allow you to spin up new types of environments when needed. I.E. for every new environment you want, you will have to add a .config. Setting environment variables at runtime can be a superior option when your tech stack requires more flexibility. I think your ./config would be good for setting up "types" of environments, but your app would be more flexible if you could define things like dsn strings and api endpoints at runtime. – Jesse Greathouse Dec 10 '15 at 18:44
  • @JesseGreathouse - I have a node.js application and I need to set the environment variables at runtime - what file would I set them in? – Roger Dodger Mar 06 '19 at 16:32
1

In addition to use of cross-env as documented above, for setting a few environment variables within a package.json 'run script', if your script involves running NodeJS, then you can set Node to pre-require dotenv/config:

{
  scripts: {
    "eg:js": "node -r dotenv/config your-script.js",
    "eg:ts": "ts-node -r dotenv/config your-script.ts",
    "test":  "ts-node -r dotenv/config -C 'console.log(process.env.PATH)'",
  }
}

This will cause your node interpreter to require dotenv/config, which will itself read the .env file in the present working directory from which node was called.

The .env format is lax or liberal:

# Comments are permitted
FOO=123
BAR=${FOO}
BAZ=Basingstoke Round About

#Blank lines are no problem
Lee Goddard
  • 10,680
  • 4
  • 46
  • 63
0

Note : In order to set multiple environment variable, script should goes like this

  "scripts": {
    "start": "set NODE_ENV=production&& set MONGO_USER=your_DB_USER_NAME&& set MONGO_PASSWORD=DB_PASSWORD&& set MONGO_DEFAULT_DATABASE=DB_NAME&& node app.js",
  },
mabdullahse
  • 3,474
  • 25
  • 23