Skip to content

.env location in addition to useDotenv parameter #10641

Description

@AlexHladin

Is there an existing issue for this?

  • I have searched existing issues, it hasn't been reported yet

Use case description

The use case is next:
I have a serverless configuration in the API folder, but my .env file exists on one directory level above, example below:

-- api
--- serverless.yml
-.env

Proposed solution (optional)

My solution for this is next: add one more parameter dotEnvFileLocation which will contain relative to serverles.yml path to .env file. The parameter name could be different, just my thoughts.

Activity

  1. mnapoli commented on Feb 4, 2022

    @mnapoli
    Contributor

    Hi, I'm interested to learn why the .env file is stored in a directory above? Is this a scenario where you have multiple services in one monorepo? Or is this something else? Thanks!

  2. AlexHladin commented on Feb 4, 2022

    @AlexHladin
    Author

    Hi @mnapoli

    Yes, it is a monorepo service, the structure looks like

    - api
    - database
    - auth
    ...
    
    serverless.yml
    .env
    
  3. mnapoli commented on Feb 5, 2022

    @mnapoli
    Contributor

    Thanks for the details! We will use this issue to track the community's interest in that feature (to anyone reading this: you can add a 👍 to the issue).

    @AlexHladin I'm also curious: what kind of values do you store in .env? Would Stage parameters (new feature introduced in v3) help?

    Or are these secret values? In that case: is there any reason not to use SSM or another remote storage? How do you share the .env in your team?

    Also is .env committed in git?

    Finally one last question: you seem to have a serverless.yml file at the root of the project: what does that file deploys? (are these shared resources like databases, etc.?)

    I have many questions because we are looking into better supporting multi-service projects. So we want to understand what limitations users may have.

  4. AlexHladin commented on Feb 5, 2022

    @AlexHladin
    Author

    Hi @mnapoli

    The main idea is to allow each developer to store their own environment variables close to the code, the SSM is not the most convenient solution here.

    The .env is not committed in git, but .env.example yes, it is just an example of what variables have to be stored.

    a serverless.yml file at the root of the project contains buckets and statically stored files in them.

  5. AlexHladin commented on Feb 14, 2022

    @AlexHladin
    Author

    Hi @mnapoli,
    Do you use like count for the community's interest in that feature? Or do you worry about resource allocation for this feature? In case you are, I can do this feature myself 😄

  6. gleidsonh commented on Mar 5, 2022

    @gleidsonh

    I'm in the same situation as @AlexHladin. I have a monorepo project that was in an old serverless version and when updating serverless to the latest version, I had this surprise: >= [email protected] launched its own environment variables and caused this problem.

    In my case, each function has a serverless.yml as they individually deploy. For this, I use Gitlab Pipeline. However, I have a serverless in the root for serverless offline.

    I don't remember why I did it with this structure, but when I did, it was the correct way. I don't remember if it's because I have some js and other python functions, or another reason, anyway, it was the only way at the time.

    To work in this latest version, I need to have a serverless.yml and .env for each function, and for the root, a total mess. A simple path to the serverless environment variables would solve this duplicate .env problem.

    Anyway, I'll study another way to merge all this in the root serverless.yml, and if I succeed, I'll come back here. However, as mentioned, I have functions in js, py, and some will use ECR, so I don't know how incompatible all this can be.

  7. gleidsonh commented on Mar 6, 2022

    @gleidsonh

    I found out why I use a serverless.yml for each function.

    One problem that "existed" but was apparently due to lack of knowledge is related to Gitlab Pipeline. When starting Pipeline, it currently uses the serverless.yml of the function itself with the command: serverless deploy --stage prod
    However, if I use a serverless.yml in the root of the project with several functions, I only need to insert the -f parameter. Apparently it will work, but I will have to test.

    But the other problem is related to sending environment variables. For env, I use the serverless-dotenv-plugin, which allows specifying which environment variables will actually be sent to the function or not.

    custom:
       dotenv:
         path: ../../../../.env
         include:
           - SOME_VAR
    

    I don't know if there would be a way to solve this in a single serverless.yml. Any idea?

  8. Kris-Pelteshki commented on May 27, 2022

    @Kris-Pelteshki

    I ran into the same issue.

    We have a monorepo and some of the env variables that I need for a serverless function are not only used by serverless, but also used elsewhere.

    For now, it looks like we'll have to store env variables in 2 locations at least instead of 1.

  9. jeanbmar commented on Jul 12, 2022

    @jeanbmar

    There are 2 features overlapping on this issue:

    • Loading a .env file that is located outside the serverless config file directory. The implementation should imo reuse the projectDir property that is already being used with monorepos. The .env name resolution rules (like choosing the right file depending on the stage) would apply normally.
    • Loading a .env file that does not follow the .env name resolution rules. e.g. loading a file named .env.development while the serverless stage is named dev. Easily doable with yml variables as long as a new property is able to accept a path / filename.

    It should be possible to combine these 2 options, ideally.

  10. gkuga commented on Aug 30, 2022

    @gkuga

    We are splitting the yaml file for CloudFormation resource limits problem and addressing with this by copying .env file to each directory. But it would be nice to use this feature.

  11. chapman-cc commented on Apr 20, 2023

    @chapman-cc

    I want to express that I want this feature as well

    I'm using serverless-compose.yml and monorepo architecture, and I think it's logical some env should be shared across services

    right now my fix is use ln .env $PWD/<resource>/.env

  12. austencollins commented on Jan 27, 2024

    @austencollins
    Member

    This sounds like a great and table-stakes idea. We've just added this into upcoming Serverless Framework V.4.

    Currently, here is how it works...

    In your configuration (e.g. serverless.yml), useDotenv can still be specified at the parent level with true, but now optionally accepts a path.

    The path can be any parent directory. In the path string, a file can be specified (.env or .env.specific) or a directory (e.g. ../../).

    If the value is true or a directory is specified (e.g. ../) a env.{stage} with the current Stage of your Service will be searched for as well as a default .env file. The variables in the env.{stage} will take priority over variables in the .env.

    Let me know if you all have any feedback.

  13. dathmart commented on Jul 25, 2024

    @dathmart

    @austencollins useDotenv apparently no longer accepts a path

    .serverless/meta.json
    "error": { "message": "Configuration error at 'useDotenv': must be equal to constant\n\nLearn more about configuration validation here: ... at async run3 (file:///Users/.../.serverless/releases/4.1.16/package/dist/sf-core.js:920:17704)", "code": "INVALID_NON_SCHEMA_COMPLIANT_CONFIGURATION" },

    I'm trying to debug a peculiar issue right now where npx sls deploy --stage=staging is using the incorrect .env file. It actually appears to be loading the env variables from a cache somewhere, although I haven't been able to locate where they are coming from.

    Additionally, the environmental variables declared in provider.environment appear to be getting exported to the PATH somehow. I tried cloning the repository to a different folder and unsetting all of the variables that were exported to the PATH, but they keep reappearing and causing sls deploy and sls print to show values that have been removed from every .env file in the repository

    serverless.yml:

    org: '[redacted]'
    app: '[redacted]'
    service: '[redacted]'
    
    useDotenv: .env.${opt:stage}
    configValidationMode: error
    
    provider:
      name: aws
      runtime: nodejs20.x
      region: ${opt:region, '[redacted]'}
      stage: ${opt:stage, 'dev'}
      versionFunctions: false
      timeout: 29
    
      apiGateway:
        minimumCompressionSize: 1024
      deploymentBucket:
        name: '[redacted]'
        serverSideEncryption: AES256
        blockPublicAccess: true
    
      environment:
        ACCOUNT_ID: ${self:custom.accountId}
        ACM_CERTIFICATE_ID: ${env:ACM_CERTIFICATE_ID}
        API_BUCKET: ${self:custom.api-bucket}
        AWS_TARGET_REGION: ${self:provider.region}
        CLIENT_PORT_OFFLINE: ${env:CLIENT_PORT_OFFLINE}
        CLOUDFRONT_DIST_DOMAIN: ${env:CLOUDFRONT_DIST_DOMAIN}
        CLOUDFRONT_PUBLIC_KEY_ID: ${env:CLOUDFRONT_PUBLIC_KEY_ID}
        COGNITO_AUTH_DOMAIN: ${env:COGNITO_AUTH_DOMAIN}
        COGNITO_CLIENT_CALLBACK_URL: ${env:COGNITO_CLIENT_CALLBACK_URL}
        COGNITO_CLIENT_ID: ${env:COGNITO_CLIENT_ID}
        COGNITO_CLIENT_NAME: ${env:COGNITO_CLIENT_NAME}
        COGNITO_CLIENT_SIGN_OUT_URL: ${env:COGNITO_CLIENT_SIGN_OUT_URL}
        COGNITO_USER_POOL_ID: ${env:COGNITO_USER_POOL_ID}
        COGNITO_USER_POOL_NAME: ${env:COGNITO_USER_POOL_NAME}
        REGION: ${self:provider.region}
        SERVER_PORT: ${env:SERVER_PORT}
        SQS_QUEUE_URL: ${self:custom.sqsQueueUrl}
      httpApi:
        payload: '2.0'
        authorizers:
          cognitoAuthorizer:
            type: jwt
            identitySource: $request.header.Authorization
            issuerUrl: ${self:custom.cognitoUserPoolUrl}
            audience:
              - ${self:provider.environment.COGNITO_CLIENT_ID}
        cors:
          allowedOrigins:
            - ${self:custom.cognitoClientCallbackURL}
            - http://localhost:3000
          allowedMethods:
            - '[redacted]'
            # ...
          allowedHeaders:
            - '[redacted]'
            # ...
          allowCredentials: true
          exposedResponseHeaders:
            - '[redacted]'
            # ...
      iam:
        role:
          statements:
            - Effect: Allow 
              Action:
                - '[redacted]'
              Resource: '[redacted]'
            # ...
    
    plugins:
      - serverless-deployment-bucket
      - serverless-offline
      - serverless-s3-local
    
    custom:
      accountId: '[redacted]'
      acmCertificateId: ${self:provider.environment.ACM_CERTIFICATE_ID}
      api-bucket: '[redacted]'
      cognitoAuthDomain: ${self:provider.environment.COGNITO_AUTH_DOMAIN}
      cognitoClientCallbackURL: ${self:provider.environment.COGNITO_CLIENT_CALLBACK_URL}
      cognitoClientName: ${self:provider.environment.COGNITO_CLIENT_NAME}
      cognitoClientSignOutURL: ${self:provider.environment.COGNITO_CLIENT_SIGN_OUT_URL}
      cognitoUserPoolARN: arn:aws:cognito-idp:${self:provider.region}:${self:custom.accountId}:userpool/${self:provider.environment.COGNITO_USER_POOL_ID}
      cognito_poolId: ${self:provider.environment.COGNITO_USER_POOL_ID}
      cognito_poolName: ${self:provider.environment.COGNITO_USER_POOL_NAME}
      esbuild:
        bundle: true
        minify: false
        watch:
          pattern: ['src/**/*.ts']
          ignore: ['.build', 'dist', 'node_modules', '.serverless']
      offline:
        useChildProcesses: true
      s3:
        host: localhost
        directory: /tmp
        port: 8002
        cors: ./cors.xml
      serverless-offline:
        httpPort: ${self:provider.environment.SERVER_PORT}
    
    functions:
      ${file(yml/functions.yml)}
    
    resources:
      - ${file(yml/cognitoResources.yml)}
      - ${file(yml/dynamoResources.yml)}
      - ${file(yml/s3Resources.yml)}
      - ${file(yml/sqsResources.yml)}
    
    package:
      patterns:
        - '!.git/**'
        - '!node_modules/**'
        - '!src/**/*.ts'
    
  14. arthurcaccavo commented on May 5, 2025

    @arthurcaccavo

    Would it be possible to load multiple .env files on different paths?

    In my case we have a monorepo with a top level .env file with information related to all projects and each project has it's own .env with specific information and It would be nice to be able to import both of them.

    maybe useDotenv could accept a list like:

    useDotenv:
      - ./configuration
      - ../configuration
  15. added theissue type on Nov 28, 2025
  16. Tsingis commented on Jan 29, 2026

    @Tsingis

    Is this currently possible without much trickery?

    Using useDotenv: ../ did not work to load .env files from parent directory.

    [!] Invalid configuration encountered
      at 'useDotenv': must be equal to constant
    
  17. Tsingis commented on Jan 30, 2026

    @Tsingis

    Would it be possible to load multiple .env files on different paths?

    In my case we have a monorepo with a top level .env file with information related to all projects and each project has it's own .env with specific information and It would be nice to be able to import both of them.

    maybe useDotenv could accept a list like:

    useDotenv:

    • ./configuration
    • ../configuration

    This would be dope!

  18. czubocha commented on Jun 3, 2026

    @czubocha
    Contributor

    Hey folks, this landed in v4.37.0.

    useDotenv now accepts a path or an array of paths in addition to the boolean. You can point it at .env files outside the service directory — exactly the monorepo / parent-directory case described here:

    useDotenv: ../shared        # load files from a sibling/parent directory
    # useDotenv:                # …or a list — earlier entries win
    #   - ./overrides.env
    #   - ../

    These load alongside the .env / .env.${stage} files already picked up automatically. useDotenv: false remains the documented opt-out.

    Docs: https://www.serverless.com/framework/docs/providers/aws/guide/serverless.yml#dotenv-files

    Closing as released - thanks for the request!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions