@mvdlei/env

The @mvdlei/env package provides a utility function define for defining and validating environment variables in TypeScript using the Zod schema.

Installation

npm install @mvdlei/env

Dependencies

The @mvdlei/env package depends on the following packages:

  • zod

Usages

Usage Env

This package is usable in React and Node.

But be aware to set your source property correctly, with vite you should use import.meta.env and with next you should use process.env.

Example

import { Env } from "@mvdlei/env";
 
const value = Env.get("NODE_ENV");
// ^ This is not type safe, because the type is `Primitive | undefined`

With options

import { Env } from "@mvdlei/env";
 
const env = Env.init({
  // default options:
  source: process.env,
  strict: false,
});
 
const value = env.get("NODE_ENV");
// ^ Primitive | undefined

Strict mode

const env = Env.init({
  strict: true,
});
 
const value = env.get("DOES_NOT_EXIST");
// ^ This will throw an error, because the variable does not exist
// Default error message: "Environment variable 'DOES_NOT_EXIST' is not defined"
// Do have note that setting your own `KEY` to `undefined` will also throw this error.

And where you want to use the environment variable, you can use the get method with a default value.

const withDefault = Env.get("NODE_ENV", "development");
// ^ Primitive | "production"

Usage Env.set

import { Env } from "@mvdlei/env";
 
const env = Env.init({
  source: process.env,
});
 
env.set("NODE_ENV", "production");

Strict mode

const env = Env.init({
  strict: true,
});
 
env.set("EXISTING", "my_value");
// ^ This will throw an error, because the variable already exists.
// Default error message: `Environment variable "${key}" is already set`

Usage define

This package is usable in React and Node.

But be aware to set your source property correctly, with vite you should use import.meta.env and with next you should use process.env.

Example

An example as used in the showcase app (here).

import { define } from "@mvdlei/env";
import { type Level } from "@mvdlei/log";
import { t } from "@mvdlei/tzod";
import { z } from "zod";
 
// Define environment variables
export const env = define({
  env: {
    NODE_ENV: z
      .string()
      .default("development")
      .transform((val) => t.string.lower(val)),
  },
  prefix: "INTERNAL_",
  prefixed: {
    INTERNAL_LOG_LEVEL: z
      .enum(["error", "warn", "info", "http", "verbose", "debug", "silly"] as const)
      .default("info")
      .transform((val) => t.string.lower(val)),
  },
});
 
// Access environment variables
const nodeEnv = env.NODE_ENV; // "development"
const logLevel = env.INTERNAL_LOG_LEVEL; // "info"

API Reference

Env

The Env class provides a set of utility methods for working with environment variables.

init(options: EnvOptions): Env

The init method is used to initialize a new Env instance with the provided options.

get(key: string, defaultValue?: Primitive): Primitive

The get method is used to get the value of an environment variable by key.

set(key: string, value: Primitive): void

The set method is used to set the value of an environment variable by key.

EnvOptions

The EnvOptions interface defines the contract for the Env class options.

Default values, providing one will override its default counterpart.

Env.init({
  // default options:
  source: process.env,
  strict: false,
});

define(options: EnvOptions<TPrefix, TPrefixed, TEnv>): Readonly<z.infer<ZodObject<TPrefixed>> & z.infer<ZodObject<TEnv>>>

The define function is used to define and validate environment variables based on the provided options.

Options

  • env: An object representing the schema for general environment variables.
  • prefix: A prefix for client-side variables.
  • prefixed: An object representing the schema for client-side environment variables.
  • isClient: A boolean indicating whether the app is running on the client (default: typeof window !== "undefined").
  • onValidationError: A callback function called when validation fails.
  • onInvalidAccess: A callback function called when a server-side environment variable is accessed on the client.
  • validate: A boolean indicating whether to skip validation of environment variables (default: false).
  • emptyStringAsUndefined: A boolean indicating whether to treat empty strings as undefined (default: false).
  • strict: An object representing the schema for strict runtime environment variables.
  • runtime: Runtime environment variables to use for validation.
  • source: Be aware that this is where the environment variables are read from. So using process.env will not work in the browser.