Node.js Foundations·From script to service

Environment and config

Load settings from the environment, validate them early and never leak secrets.

Intermediate 11 min read Lesson 2 of 300 Challenge included
What you will be able to do
  • Read settings from process.env with sensible defaults.
  • Load a .env file in development only.
  • Fail fast when a required variable is missing.
  • Strip secrets before logging configuration.

In plain English

Configuration that changes between machines, such as a database URL or a port, belongs in environment variables instead of in code. process.env holds every variable your process inherited when it started. A .env file is a local convenience you load with a library such as dotenv so you do not type variables by hand. Validate required values at startup so the server fails fast with a clear message. When you log config, redact secrets so they never end up in logs.

Step by step

  1. 1Add dotenv so a local .env file is loaded before config is read.
  2. 2Read values from process.env with defaults for optional settings.
  3. 3Write a required helper that throws when a secret is absent.
  4. 4Log a redacted copy of config so secrets never reach the output.
config.tsTypeScript
import 'dotenv/config'

function required(name: string): string {
  const value = process.env[name]
  if (!value) {
    throw new Error('Missing required environment variable: ' + name)
  }
  return value
}

export const config = {
  port: Number(process.env.PORT ?? 3000),
  databaseUrl: required('DATABASE_URL'),
  logLevel: process.env.LOG_LEVEL ?? 'info',
}

export function redactedConfig() {
  const { databaseUrl, ...rest } = config
  return rest
}

console.log(redactedConfig())

Common mistakes

  • Hard-coding a database password in source means anyone with the code has the secret.
  • Logging the full config object prints passwords and tokens into every log destination.
  • Waiting until the database connection fails makes a missing variable much harder to diagnose.
  • Committing a .env file with real values to version control leaks secrets to the repository.
Your turn

Redact a secret

Easy

Write a function that takes a config object with an apiKey field and returns a copy with apiKey replaced by "REDACTED".

JAVASCRIPT · starter
function redacted(config) {
  return config
}
Check your understanding before moving on.
Knowledge checkQuestion 1

Why is it safer to validate required environment variables at startup?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Next: Databases with Postgres
Lesson 2 of 300 · 0% of course