process.env Reads Config With Defaults

Read environment variables with string-aware defaults: coalesce missing vars, coerce numbers explicitly, and parse flag or list values safely.

JavascriptConfig Management

Code

javascriptsnippet
16 lines
// Write a variable the way a shell or test harness would, then read it back.
process.env.DEPLOY_ENV = 'staging';

const env = process.env.DEPLOY_ENV ?? 'development';
const port = Number(process.env.PORT ?? 3000);
const debug = process.env.DEBUG === 'on';
const tags = (process.env.DEPLOY_TAGS ?? '').split(',').filter(Boolean);

console.log('env:', env);
console.log('port:', port, typeof port === 'number');
console.log('debug flag:', debug);
console.log('tags:', tags.length);

// env values are always strings, so missing vars need explicit defaults
const unset = process.env.DEFINITELY_UNSET_VAR;
console.log('unset var is undefined:', unset === undefined);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

env: staging
port: 3000 true
debug flag: false
tags: 0
unset var is undefined: true

Inside the snippet

The snippet is organized around the function tags.

Configuration comes from the environment — it reads DEPLOY_ENV, PORT, DEBUG, DEPLOY_TAGS, so the same code switches behavior between environments without edits.

What to watch for

  • It is dependency-free in the strict sense — the import list, if any, is empty of packages.

Using it

The primary signature is const tags = (process.env.DEPLOY_TAGS ?? '')

Expect labeled output — env:, port:, debug flag: — when the file runs.

Key statements

const tags = (process.env.DEPLOY_TAGS ?? '').split(',').filter(Boolean);
const env = process.env.DEPLOY_ENV ?? 'development';
const port = Number(process.env.PORT ?? 3000);

Interactive Tools for This Topic

FAQ

Are there any imports to resolve outside the language?
No. Every import resolves against the language's own modules. The file defines `tags` at load time.