Next.js Discord

Discord Forum

NODE_ENV behavior inconsistency

Unanswered
Oriental posted this in #help-forum
Open in Discord
OrientalOP
Hello, I read the documentation on environment variables but I still don't understand why this is happening. Start a new project and add the following server-side code.

const env = z.object({
  NODE_ENV: z.enum(["development", "production", "test"]),
}).parse(process.env);
const assigned = process.env
const key = 'NODE_ENV'
console.log({
  direct: process.env.NODE_ENV,
  indirect: assigned.NODE_ENV,
  parsed: env.NODE_ENV,
  keyed: assigned[key],
})


The environment variable parsed by the Zod schema gets test, but not the other methods, with build it is even weirder.

Result when running NODE_ENV=test next dev,
{
  direct: 'development',
  indirect: 'development',
  parsed: 'test',
  keyed: 'development',
}

Result when running NODE_ENV=test next build, I get
{
  direct: 'production',
  indirect: 'production',
  parsed: 'test',
  keyed: 'test',
}

1 Reply

OrientalOP
This behavior isn't limited to Zod, I get the same if I use ArkType, or the following

let dynamic = null
for (const key in process.env) {
  if (key === 'NODE_ENV') {
    dynamic = process.env[key]
  }
}

console.log(dynamic) // test for both next dev and next build


What is supposed to be the "correct" behavior? Should NODE_ENV be set?