Parameters into handler.js file

I have some constants that in the handler.js file that needs to be configured different dependent on environment (dev, test, prod). For parameters in serverless.yml it is great that the syntax ${opt:region, ‘eu-west-1’} can be used. But what is best practice for variables inside handler.js file?

// Regards Anders

Define it in a custom variable file for each environment

$ cat dev.yml
stage: ${opt:stage, self:provider.stage}
region: ${opt:region, ‘eu-west-1’}
environment: development

$ cat prod.yml
stage: ${opt:stage, self:provider.stage}
region: ${opt:region, ‘eu-west-1’}
environment: production

Feed it to lambda functions, notice the environment variables I set for that lambda function:

custom: ${file(${opt:stage, self:provider.stage}.yml)}

    handler: handler.create
      environment: ${self:custom.environment}
      - http:
          path: todos
          method: post
          cors: true

Then you should be fine to reference this variable by below way in handler.js:

const Environment =  process.env.environment

So you can control to use which environment file by feeding option --stage when deploy

# use the default stage, which is dev, so serverless will pick up the variables from file `dev.yml`
sls deploy   

# feed with option --stage, so serverless will pick up the variables from file `prod.yml`
sls deploy --stage prod
1 Like

Works perfect!
Thanks for excellent guide.

1 Like