Search code examples
typescriptlambdaserverless

How to access environment variables in typescript format serverless files?


I’ve used this excellent template to get going with Node and typescript serverless/lib/plugins/create/templates/aws-nodejs-typescript at master · serverless/serverless · GitHub

In the handler definition I’m trying to reference environment variables

When I print out the variable, there is no interpolation. The variable is still ${env.CONFIG_TABLE} with the braces

"CONFIG_TABLE":"${env.CONFIG_TABLE} I would like to use environment variables for CI and .env for local development.

const serverlessConfiguration: AWS = {
  service: 'trial-service',
  frameworkVersion: '2',
  useDotenv: true,

I set the variable in the environment section of the handler. The file functions/my-function/index.ts is

import schema from './schema';
import { handlerPath } from '@libs/handlerResolver';

export default {
  handler: `${handlerPath(__dirname)}/handler.main`,
  events: [
    {
      http: {
        method: 'post',
        path: 'make-payment',
        request: {
          schema: {
            'application/json': schema
          }
        }
      }
    }
  ],
  environment: {
    CONFIG_TABLE : "${env.CONFIG_TABLE}",
  }
}

Solution

  • The solution is to access process.env. This does read from the .env file and the environment variables.

      environment: {
        CONFIG_TABLE : process.env.CONFIG_TABLE,