DEV Community

Mark Tse
Mark Tse

Posted on • Originally published at

Using dotenv with the Serverless Framework

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:


Enter fullscreen mode Exit fullscreen mode


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


service: my-service
# Required to use the new variables engine
variablesResolutionMode: 20210219

  dotenvVars: ${file(configs.js)}

    handler: src/hello.handler
      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!

Top comments (0)