Repository navigation
feat: support custom .env file locations via useDotenv - #13597
Conversation
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.
✅ Snyk checks have passed. No issues have been found so far.
💻 Catch issues earlier using the plugins for VS Code, JetBrains IDEs, Visual Studio, and Eclipse. |
📝 WalkthroughWalkthroughThis PR expands ChangesEnvironment loading with configurable dotenv paths
Estimated code review effort🎯 4 (Complex) | ⏱️ ~75 minutes Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Warning Review ran into problems🔥 ProblemsStopped 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 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. Comment |
|
@cursor review |
There was a problem hiding this comment.
✅ 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.
Summary
useDotenvnow accepts a path (or array of paths) to load additional.envfiles 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: falsenow correctly skips all.envloading. The schema previously rejectedfalsewhile the loader auto-loaded.envanyway — an invalid config that produced real behavior. The schema now acceptsfalseand the loader honors it as the documented opt-out.core:resolver:envsurfaces which.envfiles were loaded and which keys came from each. Visible withSLS_DEBUG=*. Keys only, never values.Configuration shapes
trueor omitted<serviceDir>/.env.${stage}then<serviceDir>/.envfalse.envloading skipped.<dir>/.env.${stage}(if stage set) then<dir>/.envPrecedence (highest → lowest):
process.env(system environment)<serviceDir>/.env.${stage}<serviceDir>/.env.env.${stage}beats.env)Monorepo example
With
--stage dev, precedence resolves to:api/.env.dev→api/.env→../.env.Notes
${opt:stage},${self:…}, etc.) are not resolved insideuseDotenv— the value is read before the resolver runs. Use the directory form for stage-specific custom files.useDotenvis per-service. Setting it at the top level ofserverless-compose.ymlhas no effect; each child service declares its own.${env:…}placeholders insideprovider.stagecannot reference values from any.envfile (local or custom) — stage resolution runs before.envloading.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.mdanddocs/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..envwithuseDotenv: ../in child service resolves env vars.useDotenv: falseskips loading;${env:FOO}placeholders fall back as expected;.env*files remain in the deployment zip.useDotenv: <nonexistent-path>is silently skipped, deploy succeeds.useDotenv: truecontinues to behave exactly as before (local-only loading;.env*excluded from zip).SLS_DEBUG=*, debug logs show each loaded file path and the names of its keys (no values).Summary by CodeRabbit
New Features
Documentation
Tests
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
useDotenvso services can load extra.envfiles 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: falseis now schema-valid and honored by the loader to disable all.envloading (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.envload, so${env:…}inprovider.stagecannot come from.envfiles.Resolver wiring passes
serviceConfigFile.useDotenvintoloadEnvFiles, 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.