Skip to main content

Env

Reading environment variables and validating them, with Zod schemas doing the validating. getENV throws when a variable is missing and no default was given — failing loudly at startup beats an undefined surfacing three layers deep in a request. isDev, isProd and isTest are plain NODE_ENV string comparisons, so they are cheap enough to call anywhere.

Example

import { checkEnv, isProd } from '@rtorcato/js-common/env'
import { z } from 'zod'

// Validate the whole environment once, at boot, and fail with a readable list
// of what is missing rather than an `undefined` three layers into a request.
const env = checkEnv(
z.object({
DATABASE_URL: z.string().url(),
PORT: z.coerce.number().default(3000),
})
)

env.PORT // number — coerced and defaulted
isProd() // NODE_ENV === 'production'

Import

import { RootApiEnvSchema, checkEnv, getENV } from '@rtorcato/js-common/env'

Exports

NameSummary
RootApiEnvSchemaSchema for validating the root environment variables.
checkEnvValidates the environment variables against a Zod schema.
getENVRetrieves the value of an environment variable by its key.
getNodeEnvReturns the current NODE_ENV value, or 'development' if not set.
isDevDetermines if the current environment is set to development.
isProdDetermines if the current environment is set to production.
isTestDetermines if the current environment is set to test.

See also

  • process — cwd, pid, uptime, exit, CI detection
  • node — Node version checks and optional requires
  • os — platform, arch, home and temp directories
  • console — clear or silence console output