Skip to content

Commit

Permalink
Do not re-assign process.env
Browse files Browse the repository at this point in the history
Re-assigning `process.env` substitutes the "magic object" that sets
environment variables at the process level with an ordinary JavaScript
object. This causes environment variables that are set after
`process.env` is re-assigned to not be visible to native add-ons.

See [this Node.js issue][issue] and [this reproduction case][repro]
for details.

[issue]: nodejs/node#46996
[repro]: https://github.com/unflxw/nodejs-process-env-addons-repro
  • Loading branch information
unflxw committed Mar 8, 2023
1 parent f1fba5b commit 472612d
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
14 changes: 13 additions & 1 deletion packages/next-env/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -94,7 +106,7 @@ export function loadEnvConfig(
if (combinedEnv && !forceReload) {
return { combinedEnv, loadedEnvFiles: cachedLoadedEnvFiles }
}
process.env = Object.assign({}, initialEnv)
replaceProcessEnv(initialEnv)
previousLoadedEnvFiles = cachedLoadedEnvFiles
cachedLoadedEnvFiles = []

Expand Down
9 changes: 9 additions & 0 deletions test/unit/preserve-process-env.test.ts
Original file line number Diff line number Diff line change
@@ -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()
})
})

0 comments on commit 472612d

Please sign in to comment.