What is the correct way to use .env with multi-stage config files?

amazon-alexa

#1

Is the following, the correct way to do this?

NOTE: The call to dotenv in config.local.js

config.js

module.exports = {
    custom: {
        myApiKey: process.env.MY_API_KEY
    }
 };

config.local.js

    require('dotenv').config();

    module.exports = {}

config.prod.js

module.exports = {}

app.js

const key = this.$app.$config.custom.myApiKey

.env

STAGE = "local"
MY_API_KEY = "KEY1"

When stage is ‘local’, the value from the .env file will be used. When the state is ‘prod’, the value from the lambda environment variable will be used.

Thanks,

Mark


#2

Hi Mark,

As only the exported object from config.local.js is merged into the default config.js, I’m not sure if requiring dotenv there works.

Did you run into any problems?


#3

Requiring dotenv in config.local.js does work. Please don’t change anything that would make it NOT work. I think it is a good approach and docs should include the sample for multiple stages.

config.js

module.exports = {
    custom: {
        myApiKey: process.env.MY_API_KEY
    }
 };

config.local.js

    require('dotenv').config();

    module.exports = {}

config.prod.js

module.exports = {}

app.js (or handler)

const key = this.$app.$config.custom.myApiKey || '';
const value = process.env.ANOTHER_KEY || '';

.env

STAGE = "local"
MY_API_KEY = "KEY1"
ANOTHER_KEY = "value"

Lambda Function configuration