Environment Variables
Node에서 환경변수를 설정해보자.
About
This post shows how to inject environment variables to your Node application.
Injecting Environment Variables
Inject within commands
$ NODE_ENV=dev npm start
Just put the environment variable in key=value
format at the beginning.
Injecting multiple variables
$ KINESIS_STREAM_NAME=litsynp-stream-dev AWS_REGION=ap-northeast-2 npm start
Inject in package.json
package.json
Same as above; but put it in the scripts
section of package.json
.
// ...
"scripts" : {
"start": "node index.js",
"test": "NODE_ENV=test mocha --reporter spec"
}
// ...
Reading Environment Variables
const KINESIS_STREAM_NAME = process.env.KINESIS_STREAM_NAME
This is how you read it. just reference process.env.ENV_NAME
to read a specific variable.
The way I prefer is like creating a config file.
export const KINESIS_STREAM_NAME = process.env.KINESIS_STREAM_NAME ?? 'test-stream-name'
export
- Export the variable to be used in other JS files. (This is ESM syntax. CJS, AMD, UMD, ESM)??
- 'Nullish coalescing operator'. Returns right-hand side operand when left-hand side operand isnull
orundefined
. I add right-hand side operand as the fallback value in case the environment variable is not provided.
import { KINESIS_STREAM_NAME } = './config'
Import the variable from the config file and use it!
Credits
Last updated
Was this helpful?