diff --git a/packages/next-env/index.ts b/packages/next-env/index.ts index a36abfc194a84..72a92282683fb 100644 --- a/packages/next-env/index.ts +++ b/packages/next-env/index.ts @@ -20,6 +20,18 @@ type Log = { error: (...args: any[]) => void } +function replaceProcessEnv(sourceEnv: Env) { + Object.keys(process.env).forEach((key) => { + if (sourceEnv[key] === undefined || sourceEnv[key] === '') { + delete process.env[key] + } + }) + + Object.entries(sourceEnv).forEach(([key, value]) => { + process.env[key] = value + }) +} + export function processEnv( loadedEnvFiles: LoadedEnvFiles, dir?: string, @@ -94,7 +106,7 @@ export function loadEnvConfig( if (combinedEnv && !forceReload) { return { combinedEnv, loadedEnvFiles: cachedLoadedEnvFiles } } - process.env = Object.assign({}, initialEnv) + replaceProcessEnv(initialEnv) previousLoadedEnvFiles = cachedLoadedEnvFiles cachedLoadedEnvFiles = [] diff --git a/test/unit/preserve-process-env.test.ts b/test/unit/preserve-process-env.test.ts new file mode 100644 index 0000000000000..cbddc233040e7 --- /dev/null +++ b/test/unit/preserve-process-env.test.ts @@ -0,0 +1,9 @@ +import { loadEnvConfig } from '../../packages/next-env/' + +describe('preserve process env', () => { + it('should not reassign `process.env`', () => { + const originalProcessEnv = process.env + loadEnvConfig('.') + expect(Object.is(originalProcessEnv, process.env)).toBeTrue() + }) +})