aws-lambdaserverless-frameworkmonorepodotenvnpm-workspaces

How do I configure Serverless Framework for dotenv in a monorepo for specific sub-folders?


I've got a basic monorepo using npm workspaces. Folder structure is like so:

my-app/
├── node_modules
├── packages/
│   └── lambda/
│       ├── .env (the one I want)
│       ├── package.json
│       └── prototype.ts
├── .env (the one that works)
├── package.json
└── serverless.yml

My serverless.yml file:

service: prototype-serverless-api
frameworkVersion: '3'
useDotenv: true

provider:
  name: aws
  runtime: nodejs18.x

plugins:
  - serverless-plugin-typescript
  - serverless-offline
  - serverless-dotenv-plugin

functions:
  routesHandler:
    handler: ./packages/lambda/prototype.routesHandler
    events:
      - http:
          path: /movies
          method: get
          cors: true

custom:
  serverlessPluginTypescript:
    tsConfigFileLocation: './tsconfig.base.json'

Serverless only exists in my project for local debugging, and it works as-is with serverless.yml in the root of the repo, but it's also forcing me to place my .env file in the root and won't allow me to place individual .env files into different projects inside of the /packages folder, like I've got in the image above. It only recognizes the env vars if it's in the root.

Really, I'd like serverless.yml to also reside inside the /packages/lambda folder if possible, since that's the only place it's relevant.

Is there a way to do this?


Solution

  • Bah, got it...nevermind. This at the top of my lambda file:

    import * as dotenv from "dotenv";
    dotenv.config({ path: "packages/lambda/.env" });