Environment variables

Learn how to use environment variables with Serverless and AWS Lambda. These allow you to store things like database connection settings and API keys. Environment variables can be shared across multiple functions or you can limit them to specific functions only.


The first way of defining environment variables is by adding them to the provider section of the serverless.yml config file.

  name: aws
  runtime: nodejs6.10
  stage: dev
  region: eu-west-1
  profile: savjeebe-demo

  # Available to ALL functions in your service.
    GOOGLE_MAPS_API_KEY: key1234

All variabels that are defined here will be available to all the functions in your project (service).

Scoped to function

The second way is by adding them to a specific function:

    handler: fileName.handler
      - http:
          path: myfunction
          method: GET
      OTHER_API_KEY: key56789

Environment variables defined here will only be available to this function. You can also overwrite global environment variables that you defined in the provider section.

Using them in node.js

After defining the environment variables you can use them in your Lambda functions. Each of your variables is added to the process.env object and can be accessed like this:

module.exports.handler = (event, context, callback) => {

  // It has access to global env variables

  // And also to local scoped variables

  // Some business logic here
  // & calling the callback function

Useful resources