Ken
Ken

Reputation: 3141

How to properly call multiple environment variables within a variable definition in Node

I have two environment variables that I have saved in my local local.env.js file. I'd like to use them in place of the username and password in the following code:

var admins = {
  'frank': { password: 'mypassword' },
   };

When I use the code below, I get an error (Unexpected token .):

var admins = {
    process.env.BASIC_AUTH_USER: {password: process.env.BASIC_AUTH_PASSWORD},
    };

Any suggestions on how to do this correctly?

Upvotes: 0

Views: 369

Answers (3)

jfriend00
jfriend00

Reputation: 708056

In ES5 and earlier, a static object declaration cannot use a "computed" value for a property name - it must be a string literal. So, you have to use an actual line of code to assign the property using the obj[computedPropName] = value; syntax. In your specific case, that would look like this:

var admins = {};
admins[process.env.BASIC_AUTH_USER] = {password: process.env.BASIC_AUTH_PASSWORD};

In ES6, you can use a computed value in a static declaration if you enclose it in the array syntax like this:

var admins = {[process.env.BASIC_AUTH_USER]: {password: process.env.BASIC_AUTH_PASSWORD}};

See this description of new ES6 features and this MDN reference for some further description of this feature.

Portions of ES6 are available in some of the latest version of browsers, in runtime environments like node.js and, of course, you can use transpilers to code in ES6, but transpile to ES5 compatible code for many features. We are, of course, a ways away from being able to rely on native ES6 support for general cross browser use (thus the interest in transpilers now).

Upvotes: 1

probinson
probinson

Reputation: 361

Try this admins = {}; admins[process.env.BASIC_AUTH_USER] = {password: process.env.BASIC_AUTH_PASSWORD};

Upvotes: 1

Alex McMillan
Alex McMillan

Reputation: 17962

You can use array-like-notation, like so:

var admins = {};

admins[process.env.BASIC_AUTH_USER] = {
    password: process.env.BASIC_AUTH_PASSWORD
};

If BASIC_AUTH_USER is "Frank" and BASIC_AUTH_PASSWORD is "potatosalad" then you will end up with an object like this:

admins: {
    Frank: {
        password: 'potatosalad'
    }
}

Upvotes: 1

Related Questions