Does ConfigModule caching in NestJS interfere with .env updates during development?
0 reputation · 18 Jan 2020, 09:38 UTC
0 reputation · 18 Jan 2020, 09:38 UTC
Establish a repeatable NestJS development environment where environment variables can be adjusted without rebuilding containers or restarting the application.
The NestJS ConfigModule offers a cache option that stores configuration values after the first load. It is unclear whether enabling this cache prevents changes to .env files from being picked up during hot‑reload development, and whether disabling it introduces performance overhead or inconsistent values across requests.
34775 reputation · 18 Jan 2020, 12:16 UTC
No, ConfigModule caching does not interfere with .env updates when using nest start --watch. This is because the NestJS CLI triggers a full process restart upon detecting file changes, which clears the in-memory cache and forces a fresh reload of the environment variables.
The cache: true option in ConfigModule stores configuration values in an internal memory map. This cache persists for the lifetime of the Node.js process. Because hot-reload mechanisms (like --watch) kill the existing process and spawn a new one, the cache is naturally wiped, and the updated .env file is read during the new bootstrap sequence.
Caching only blocks updates if you are modifying the .env file while the application is running without a process restart. In such a scenario, ConfigService.get() will continue to return the value captured at startup.
cache: false) in development introduces negligible overhead. Most lookups resolve via process.env, which is highly efficient for typical development workloads..env files are typically injected at the container start. Even with cache: false, changes to a host-side .env file will not be reflected unless the file is volume-mounted and the process is restarted, as the OS environment variables are set when the container is initialized.For a repeatable development setup, use the following configuration to ensure consistency across different environments:
ConfigModule.forRoot({
isGlobal: true,
cache: true, // Keep enabled for production parity
envFilePath: '.env',
})
Since nest start --watch handles the restart, keeping cache: true is generally acceptable. However, if you use a custom runtime configuration loader that avoids process restarts, set cache: false.
nest start --watch..env file and save.Diagnostic Note: Are you using a custom load function in ConfigModule to fetch variables from an external vault or database? If so, the caching behavior may differ from standard .env file loading.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.