Skip to content

feat: support custom .env file locations via useDotenv - #13597

Merged
czubocha merged 12 commits into
mainfrom
usedotenv-custom-paths
May 27, 2026
Merged

czubocha merged 12 commits into
mainfrom
usedotenv-custom-paths

Conversation

@czubocha

@czubocha czubocha commented May 20, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • useDotenv now accepts a path (or array of paths) to load additional .env files from a custom location, on top of the local .env/.env.${stage} already loaded automatically. Closes .env location in addition to useDotenv parameter #10641.
  • useDotenv: false now correctly skips all .env loading. The schema previously rejected false while the loader auto-loaded .env anyway — an invalid config that produced real behavior. The schema now accepts false and the loader honors it as the documented opt-out.
  • Debug logging at core:resolver:env surfaces which .env files were loaded and which keys came from each. Visible with SLS_DEBUG=*. Keys only, never values.

Configuration shapes

# Equivalent to omitting `useDotenv` — local .env files only.
useDotenv: true

# Explicit opt-out: disable all .env loading.
useDotenv: false

# Single custom path (file or directory), relative to the service directory.
useDotenv: ../shared

# Multiple paths. Earlier entries beat later ones for shared keys.
useDotenv:
  - ./overrides.env
  - ../
Value What gets loaded
true or omitted Local <serviceDir>/.env.${stage} then <serviceDir>/.env
false Nothing. All .env loading skipped.
File path Locals and exactly that file. No stage-suffix probing on the path.
Directory path Locals and <dir>/.env.${stage} (if stage set) then <dir>/.env
Array of paths Each entry processed in order; earlier entries beat later ones on overlap.
Missing path Silently skipped.

Precedence (highest → lowest):

  1. process.env (system environment)
  2. Local <serviceDir>/.env.${stage}
  3. Local <serviceDir>/.env
  4. Custom entries in array order (within a directory entry, .env.${stage} beats .env)

Monorepo example

project/
├── .env                  # shared across services
└── api/
    ├── serverless.yml    # useDotenv: ../
    ├── .env              # api-specific overrides
    └── .env.dev          # api-specific stage overrides

With --stage dev, precedence resolves to: api/.env.dev → api/.env → ../.env.

Notes

  • Path strings are taken literally. Serverless variable placeholders (${opt:stage}, ${self:…}, etc.) are not resolved inside useDotenv — the value is read before the resolver runs. Use the directory form for stage-specific custom files.
  • useDotenv is per-service. Setting it at the top level of serverless-compose.yml has no effect; each child service declares its own.
  • ${env:…} placeholders inside provider.stage cannot reference values from any .env file (local or custom) — stage resolution runs before .env loading.
  • The loader is tolerant: missing files, unreadable paths, and dotenv parse errors are skipped silently. Detail is available at debug level for diagnosis.

Docs

  • docs/sf/providers/aws/guide/serverless.yml.md — new "Dotenv files" section under root properties with the full reference.
  • docs/sf/guides/upgrading-v4.md and docs/sf/guides/variables/env-vars.md — short pointers to the reference.

Test plan

  • npm run test -w @serverlessinc/sf-core — loader unit tests + router resolver fixtures pass.
  • npm run test -w @serverless/framework — schema validation + packaging plugin tests pass.
  • Monorepo repro: parent .env with useDotenv: ../ in child service resolves env vars.
  • Array form with overlapping keys: earlier entry wins; keys unique to a later entry still load.
  • useDotenv: false skips loading; ${env:FOO} placeholders fall back as expected; .env* files remain in the deployment zip.
  • useDotenv: <nonexistent-path> is silently skipped, deploy succeeds.
  • useDotenv: true continues to behave exactly as before (local-only loading; .env* excluded from zip).
  • With SLS_DEBUG=*, debug logs show each loaded file path and the names of its keys (no values).

Summary by CodeRabbit

  • New Features

    • Improved dotenv handling: automatic loading of .env and .env.[stage], opt-out support, and custom .env locations via useDotenv (true/false/single path/array).
  • Documentation

    • Clarified what sources populate ${env:...} and the precedence order (system env > local .env files > custom paths) and useDotenv behavior.
  • Tests

    • Added extensive tests covering dotenv loading semantics, custom paths, precedence, opt-out, and edge cases.

Review Change Stack


Note

Medium Risk
Changes early config/env resolution used by ${env:…} across services; behavior is well-tested and mostly additive, but wrong paths or precedence assumptions could shift deployed config subtly.

Overview
Extends useDotenv so services can load extra .env files from custom paths (single file, directory, or ordered array) on top of the automatic local .env / .env.${stage} behavior—aimed at monorepos and shared env files.

useDotenv: false is now schema-valid and honored by the loader to disable all .env loading (local and custom), restoring the v3 opt-out semantics that v4 had effectively ignored.

The core loader defines a clear precedence chain: process.env → local stage .env → local .env → custom paths (earlier array entries win on overlap; file paths load exactly that file without stage-suffix probing). Stage is still resolved before any .env load, so ${env:…} in provider.stage cannot come from .env files.

Resolver wiring passes serviceConfigFile.useDotenv into loadEnvFiles, with debug logging (paths and key names only) and tolerant handling of missing or unreadable paths. Docs add a Dotenv files reference; schema and broad unit/integration tests cover shapes, precedence, opt-out, and edge cases.

Reviewed by Cursor Bugbot for commit d184cb7. Bugbot is set up for automated code reviews on this repo. Configure here.

czubocha added 11 commits May 20, 2026 15:48
Add tests covering existing useDotenv behavior so it cannot regress
when the schema and loader change in follow-up commits.

- dotenv-explicit-true fixture: explicit useDotenv: true behaves
  identically to omitting the key.
- dotenv-stage-from-env-file fixture: stage resolution does not see
  .env values because env files load after stage resolution.
- loadEnvFiles unit tests: missing files are a silent no-op, system
  env wins over file values, .env.${stage} overrides .env.
- use-dotenv schema test: current const: true rejects strings,
  arrays, false, numbers, objects, null.
Widen the useDotenv top-level schema from const: true to anyOf
[const: true, non-empty string, non-empty array of non-empty strings].
Custom paths are documented to load with lower precedence than the
local files.

This is the schema half of GitHub issue #10641 (custom .env location
support). The loader is updated in a follow-up commit; users will
still see local .env / .env.${stage} loaded as before until then.

The schema uses anyOf rather than oneOf because the runtime AJV
configuration uses coerceTypes: 'array', which makes oneOf match
multiple branches for boolean true (coerced into string and array
forms). The matching use-dotenv schema test is updated to reflect
the new accept list and documents the AJV coercion behavior.
Extend loadEnvFiles to accept a useDotenv argument and add a helper
that loads each custom path entry. Wire the resolver pipeline to pass
serviceConfigFile.useDotenv through.

Behavior summary (precedence highest -> lowest, first-write-wins):
  1. process.env (system)
  2. local .env.\${stage} (loaded first locally)
  3. local .env
  4. custom entry[0] (.env.\${stage} then .env if directory; the file
     itself if file)
  5. custom entry[N] ...

Files are resolved against configFileDirPath. Missing paths and
missing files inside a custom directory are silently skipped, matching
the existing behavior for missing local .env files. Path strings are
treated literally (no Serverless variable resolution) because
useDotenv is read before the main resolver runs. Users wanting
stage-specific custom files should point useDotenv at a directory
containing .env.\${stage}.

This completes the runtime half of GitHub issue #10641.
Add six router fixtures and a dozen loader unit tests for the
custom-path feature:

- dotenv-custom-path-directory: directory mode loads .env.${stage}
  then .env; local files beat the custom directory for shared keys.
- dotenv-custom-path-file: file mode loads exactly the named file and
  does NOT probe for <file>.${stage}.
- dotenv-custom-path-array: earlier array entries win for shared keys
  (first-write-wins).
- dotenv-custom-path-array-with-file-entry: a single array can mix
  file and directory paths.
- dotenv-custom-path-missing: a nonexistent path is silently skipped.
- dotenv-custom-path-system-env-wins: process.env still beats values
  from a custom path.

The loadEnvFiles unit tests cover the same matrix in isolation —
useDotenv: true behaves like an omitted value, missing paths skip
silently, directory vs file semantics differ as documented, mixed
array entries work, locals still beat custom, system env still beats
both.
Extend the "Environment Variables Loaded By Default" section of the
V.4 upgrade guide with a subsection covering the new useDotenv path
and array forms. Includes a monorepo example matching the original
GitHub issue (#10641), the file vs. directory vs. array semantics,
precedence vs. local files, and a note that path strings are taken
literally (no Serverless variable resolution).
The upgrading-v4 section had grown into a small reference manual. Move
the detailed coverage (path semantics, precedence, edge cases) to
docs/sf/guides/variables/env-vars.md — the natural home for it next to
\${env:...} resolution syntax — and replace the upgrade-guide section
with a brief pointer + link.

This also fills a pre-existing doc gap: env-vars.md previously had no
section on how .env files are auto-discovered at all.
The variables/env-vars.md page documents the \${env:...} variable
resolver syntax, not config-side .env file loading mechanics. The
correct home for useDotenv mechanics is the serverless.yml reference,
alongside other top-level properties like stages: and params:, which
previously had no useDotenv entry at all.

- docs/sf/providers/aws/guide/serverless.yml.md: add a "Dotenv files"
  section under Root properties with the full reference (path shapes,
  precedence, edge cases).
- docs/sf/guides/variables/env-vars.md: trim back to its original
  scope (\${env:...} syntax) with a one-sentence pointer at the new
  reference.
- docs/sf/guides/upgrading-v4.md: point at the new reference location.
Add loader unit tests for edges that were not previously covered:

- Absolute path (directory) — works because path.resolve(base, abs)
  ignores the base when the second arg is absolute.
- Absolute path (file) — same, but uses file mode.
- Path traversal with .. — works, no sandbox boundary, by design (the
  monorepo use case requires escaping the service directory).
- Malformed .env content — garbage lines are silently skipped by
  dotenv; valid KEY=value lines around them still load.
- Comments-only and empty .env files — silent no-op.
loadEnvFiles previously called dotenv.config silently. There was no
way to confirm which files actually loaded or which keys came from
which file.

Wrap dotenv.config in a small helper that emits a debug log line at
every outcome:

- Successful load: file path + the names (never values) of the keys
  that were set.
- File existed but yielded no keys (empty / comments-only): file path
  plus "no keys parsed".
- dotenv.config returned an error: file path plus the error message.

All three paths log at debug level. The loader has a tolerant
silently-skip personality (missing files, schema-coerced bogus paths,
`quiet: true` to dotenv itself); the new logging stays consistent
with that — users opt in to the diagnostic detail with debug logging
(e.g. SLS_DEBUG=*).

Tests cover the success path (file path + key names appear, key
values do not), the no-keys-parsed path, and the dotenv-error path
(via a re-imported module with a mocked dotenv).
loadCustomEnvFiles passes the result of existsSync but then calls
statSync without a guard. If statSync throws — for example because of
a permission glitch or a TOCTOU race where the path disappears between
the two calls — the whole resolver pipeline crashes. The user-visible
result is an opaque deploy failure for what should have been a silent
"that path is not loadable, move on".

Wrap statSync in a try/catch that mirrors the existing existsSync
guard: skip the custom entry, emit a debug breadcrumb so users
running with SLS_DEBUG=* can see why their custom path was skipped.

This restores the loader's tolerant "silently skip on any path
failure" contract across all failure modes.

Found in code review.
The v3 docs and the schema's intent have always defined useDotenv: false
as the off state for .env loading. v4 unintentionally broke this: the
schema rejected false outright (const: true only), but the loader still
auto-loaded .env files regardless of the schema warning. Users running
with useDotenv: false saw their config flagged as invalid yet still got
their .env values loaded — undefined, contradictory behavior.

Restore the documented contract:

- Schema accepts false via { const: false } in the anyOf list. const
  does not trigger AJV's coerceTypes, so the literal boolean reaches
  the loader unmutated.
- Loader early-returns on useDotenv === false (strict equality). All
  .env loading is skipped — local and custom alike. Other falsy values
  (null, 0, the string 'false' after coercion, undefined) do NOT
  trigger the opt-out; only the literal boolean does.
- Tests cover the schema acceptance, value preservation, loader
  skip-behavior, and the strict-equality guards against coercion edge
  cases. A new router fixture (dotenv-disabled) exercises the
  end-to-end flow.
- Docs update the serverless.yml reference to document the false value.
@Mmarzex

Mmarzex commented May 20, 2026 •

Copy link
Copy Markdown
Contributor

✅ Snyk checks have passed. No issues have been found so far.

Status Scan Engine Critical High Medium Low Total (0)
✅ Open Source Security 0 0 0 0 0 issues
✅ Licenses 0 0 0 0 0 issues
✅ Code Security 0 0 0 0 0 issues

💻 Catch issues earlier using the plugins for VS Code, JetBrains IDEs, Visual Studio, and Eclipse.

@coderabbitai

coderabbitai Bot commented May 20, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This PR expands useDotenv from a boolean flag to support loading additional .env files from custom paths (files, directories, or arrays), with defined precedence: system process.env wins, then local .env files, then custom paths. Default behavior remains automatic for .env and .env.${stage}.

Changes

Environment loading with configurable dotenv paths

Layer / File(s) Summary
Config schema for useDotenv
packages/serverless/lib/config-schema.js, packages/serverless/test/unit/lib/classes/config-schema-handler/use-dotenv.test.js
useDotenv schema updated from const: true to anyOf validator accepting true, false, non-empty path strings, or arrays of non-empty paths; unit tests verify acceptance/rejection and AJV coercion behavior.
Environment file loader with custom path support
packages/sf-core/src/lib/resolvers/env.js
loadEnvFiles now accepts useDotenv parameter; loads .env files with lower-precedence custom paths via loadCustomEnvFiles, normalizes path inputs, handles directory-vs-file distinction, skips missing paths silently, uses statSync TOCTOU-guard, and centralizes dotenv.config calls through loadDotenvFile debug wrapper.
Resolver manager wiring and integration
packages/sf-core/src/lib/resolvers/index.js
createResolverManager now forwards serviceConfigFile.useDotenv to loadEnvFiles alongside stage and config directory.
Unit test suite for loadEnvFiles
packages/sf-core/tests/unit/resolvers/loadEnvFiles.test.js
Comprehensive tests covering missing-file no-ops, baseline loading, useDotenv: false strict opt-out semantics, custom paths (files/directories/arrays), stage probing, first-write-wins ordering, system-env precedence, edge-case path handling, tolerant .env parsing, and debug-logging behavior with error scenarios.
Integration tests and fixtures
packages/sf-core/tests/resolvers/router.test.js, packages/sf-core/tests/resolvers/env/*/
Router integration tests for all useDotenv modes (explicit true, false, directory paths, file paths, arrays, mixed entries, missing paths, system-env precedence); accompanying .env fixtures and serverless.yml / resolved-serverless.yml configs documenting feature behavior across scenarios.
Documentation updates
docs/sf/guides/upgrading-v4.md, docs/sf/guides/variables/env-vars.md, docs/sf/providers/aws/guide/serverless.yml.md
Guides clarify automatic .env / .env.${stage} loading and document useDotenv for custom paths, including precedence rules and timing constraints (stage resolution before dotenv loading).

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~75 minutes

Poem

🐰 Hops with glee through dotenv's array,
Custom paths now light the way,
System env first, then locals near,
Extra files load, but skip when clear,
A rabbit cheers: "No more missing keys!"

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title 'feat: support custom .env file locations via useDotenv' accurately describes the main feature—extending useDotenv to accept custom path(s) for loading .env files from non-default locations.
Linked Issues check ✅ Passed The PR fully implements the objective from #10641: useDotenv now accepts file/directory paths relative to serverless.yml, loads from custom locations with correct precedence (local files override custom ones), silently skips missing paths, and supports both single and multiple path entries.
Out of Scope Changes check ✅ Passed All changes align with the core objective: schema updates, resolver implementation, tests, and documentation for useDotenv custom-path support. No unrelated modifications detected.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch usedotenv-custom-paths

Warning

Review ran into problems

🔥 Problems

Stopped waiting for pipeline failures after 30000ms. One of your pipelines takes longer than our 30000ms fetch window to run, so review may not consider pipeline-failure results for inline comments if any failures occurred after the fetch window. Increase the timeout if you want to wait longer or run a @coderabbit review after the pipeline has finished.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@czubocha czubocha changed the title feat(sf-core): support custom .env file locations via useDotenv feat: support custom .env file locations via useDotenv May 20, 2026
@czubocha

Copy link
Copy Markdown
Contributor Author

@cursor review

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Bugbot reviewed your changes and found no new issues!

Comment @cursor review or bugbot run to trigger another review on this PR

Reviewed by Cursor Bugbot for commit d184cb7. Configure here.

@czubocha
czubocha merged commit 09792dd into main May 27, 2026
11 of 12 checks passed
@czubocha
czubocha deleted the usedotenv-custom-paths branch May 27, 2026 13:04
@github-actions github-actions Bot locked and limited conversation to collaborators May 27, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

.env location in addition to useDotenv parameter

2 participants