Matt Boyle
Matt Boyle

Reputation: 385

Changing the value of a key value pair to an enviromental variable in Node JS

module.exports = {
  app_uri: 'http://localhost:3000',
  redirect_uri: '/redirect',

 id: 'user1',
 secret: "client_secretValue",
  ...
};

I have inherited the above code. I would like to change the "secret" to be read from an environment variable. I have stored it in LOCAL_SECRET and I can successfully access it through process.env.LOCAL_SECRET.

What is the correct way to add it to the value pair above? Changing it to secret:env.process.LOCAL_SECRET doesn't work and I'm not sure why.

Upvotes: 0

Views: 1330

Answers (3)

Juan Picado
Juan Picado

Reputation: 1996

I would use either dotenv or cross-env.

cross-env fits pretty well if you run your scripts via npm or some bash script.

"start": "cross-env SECRET=secret && npm run server"

dot-evn fits much better if you likes the approach of config files

  1. Create a .env file in your root

    SECRET=secret

  2. In your first script call, before any module that use your SECRET key

    require('dotenv').config();

  3. dotenv will mix your .env content within your env variables.

    module.exports = {
     app_uri: 'http://localhost:3000',
      redirect_uri: '/redirect',
      id: 'user1',
     secret: process.env.SECRET,
     ...
    };
    

Upvotes: 3

maheshiv
maheshiv

Reputation: 1858

You can do it

 module.exports = {
  app_uri: 'http://localhost:3000',
  redirect_uri: '/redirect',

  id: 'user1',
  secret: process.env.LOCAL_SECRET || "client_secretValue",
   ...
 };

OR Use dotenv node module (https://www.npmjs.com/package/dotenv)

You can create .env file(in project root) and add environment variables there and use it in

module.exports = {
  app_uri: 'http://localhost:3000',
  redirect_uri: '/redirect',

  id: 'user1',
  secret: process.env.LOCAL_SECRET,
   ...
 };

Upvotes: 1

Alberto Zaccagni
Alberto Zaccagni

Reputation: 31560

env is an attribute of process: process.env.LOCAL_SECRET.

https://nodejs.org/api/process.html#process_process_env

Upvotes: 2

Related Questions