Search code examples
aws-lambdaenvironment-variablesserverless-frameworkserverlessdotenv

Serverless stage environment variables using dotenv (.env)


I'm new to serverless, So far I was be able to deploy and use .env for the app.

then, under provider in stage property in serverless.yml file, I change it to different stage. I also made new.env.{stage}.

after re-deploy using sls deploy, It still reads the default .env file.

the documentation states:

The framework looks for .env and .env.{stage} files in service directory and then tries to load them using dotenv. If .env.{stage} is found, .env will not be loaded. If stage is not explicitly defined, it defaults to dev.

So, I still don't understand "If stage is not explicitly defined, it defaults to dev". How to explicitly define it?


Solution

  • The dotenv File is choosen based on your stage property configuration. You need to explicitly define the stage property in your serverless.yaml or set it within your deployment command.

    This will use the .env.dev file

     useDotenv: true
     provider:
      name: aws
      stage: dev # dev [default], stage, prod
      memorySize: 3008
      timeout: 30
    

    Or you set the stage property via deploy command. This will use the .env.prod file

    sls deploy --stage prod