DEV Community

loading...

Using dotenv with the Serverless Framework

neverendingqs profile image Mark Tse Originally published at blog.neverendingqs.com ・2 min read

In my previous post, I advised that the serverless-dotenv-plugin will no longer be able to load environment variables in time to resolve env variables in your service files (e.g. serverless.yml). In this post, I want to go into details on how you can use dotenv without the plugin.

With the Serverless Framework, you can use the file variable to dynamically evaluate variables by executing JavaScript code. Leveraging this feature, you can get the Serverless Framework to run any arbitrary code, such as calling dotenv to load environment variables! See how MY_ENV_VAR is loaded into the framework below:

.env.local:

MY_ENV_VAR=loaded-by-dotenv
Enter fullscreen mode Exit fullscreen mode

configs.js:

const dotenv = require('dotenv');

module.exports = async ({ options, resolveConfigurationProperty }) => {
  // Load env vars into Serverless environment
  // You can do more complicated env var resolution with dotenv here
  const envVars = dotenv.config({ path: '.env.local' }).parsed;
  return envVars;
};
Enter fullscreen mode Exit fullscreen mode

serverless.yml:

service: my-service
# Required to use the new variables engine
# https://www.serverless.com/framework/docs/providers/aws/guide/variables#exporting-a-function
variablesResolutionMode: 20210219

custom:
  dotenvVars: ${file(configs.js)}

functions:
  hello:
    handler: src/hello.handler
    environment:
      MY_ENV_VAR: ${env:MY_ENV_VAR}
Enter fullscreen mode Exit fullscreen mode

When the Serverless Framework sees ${file(configs.js)}, the variables resolver will call the function exported in configs.js. The JavaScript code there includes a call to dotenv.config(), which will load all environment variables defined in .env.local. Because this loads the environment variables into the process, plugins will also have access to them.

With a for loop, you can load multiple dotenv files (e.g. .env and .env.local), or with options.stage, you can load files based on the value of the --stage parameter. You can also load any dotenv plugins you may be interested in using, such as dotenv-expand. Because you are able to execute arbitrary JavaScript code, you are only limited by what you can do in JavaScript!

You can find a full example is available at neverendingqs/serverless-dotenv-example. Got questions or want to see more content like this? Check out neverendingqs/ask-me-anything!

Discussion (0)

Forem Open with the Forem app