env-var

repository·master·Indexed 20 days ago

https://github.com/evanshortiss/env-var

A lightweight Node.js and web application library for the verification, sanitization, and type coercion of environment variables. It provides a chainable API to enforce requirements, set defaults, and parse values into types such as integers, floats, booleans, JSON, and URLs. Includes TypeScript support, custom accessor extensions, and integration capabilities for web bundlers like Vite and loaders like dotenv.

Tokens
5K
Snippets
24
Records
24
Agent score
69%

What's inside env-var

  1. Get started with env-var in Node.js (TypeScript)

    master

    For TypeScript users, env-var provides type safety. When using accessors like .asIntPositive(), the returned value is typed accordingly (e.g., number). If the variable is missing or fails validation, an EnvVarError is thrown.

    import * as env from 'env-var';
    
    // Read a PORT environment variable and ensure it's a positive integer.
    const PORT: number = env.get('PORT').required().asIntPositive();
  2. Use env-var in Web Applications (Vite, etc.)

    master

    Web bundlers like Vite often do not expose process.env and instead use specific conventions (like import.meta.env). To use env-var in these environments, use the from() function to map your bundler's environment object into an env-var instance.

    import { from } from 'env-var'
    
    const env = from({
      BASE_URL: import.meta.env.BASE_URL,
      VITE_CUSTOM_VARIABLE: import.meta.env.CUSTOM_VARIABLE
    })
  3. Use a custom logger with env-var

    master

    You can provide a custom logging function to env-var to control how logs are handled (e.g., filtering by log level or using a specific logging library like pino).

    When initializing the environment with from(source, defaults, logger), the logger function receives two arguments:

    1. varname: The name of the environment variable being read (e.g., "API_KEY").
    2. str: The log message (e.g., "verifying variable value is not empty").
    const pino = require('pino')()
    const customLogger = (varname, str) => {
      // varname is the name of the variable being read, e.g "API_KEY"
      // str is the log message, e.g "verifying variable value is not empty"
      pino.trace(`env-var log (${varname}): ${str}`)
    }
    
    const { from } =  require('env-var')
    const env = from(process.env, {}, customLogger)
    
    const API_KEY = env.get('API_KEY').required().asString()
  4. Get started with env-var in Node.js (JavaScript)

    master

    In Node.js, you can use env.get() to retrieve environment variables. You can chain methods to enforce requirements (like .required()), perform transformations (like .convertFromBase64()), or provide defaults (like .default()), and finally call an accessor (like .asString() or .asPortNumber()) to get the coerced value.

    const env = require('env-var');
    
    // Throws error if DB_PASSWORD is missing, decodes from base64, and returns string
    const PASSWORD = env.get('DB_PASSWORD')
      .required()
      .convertFromBase64()
      .asString();
    
    // Uses default '5432' if PORT is not defined, and validates it is a port number
    const PORT = env.get('PORT').default('5432').asPortNumber();
  5. Enable logging for environment variables

    master

    Logging is disabled by default to prevent accidental leakage of secrets. To enable it, you must create an instance using from() and pass a logger.

    Built-in Logger: If you use the built-in logger, it will only print logs when NODE_ENV is not set to prod or production.

    const { from, logger } =  require('env-var')
    const env = from(process.env, {}, logger)
    
    const API_KEY = env.get('API_KEY').required().asString()
  6. Integrate dotenv with env-var

    master

    You can use dotenv to load environment variables from a .env file before accessing them with env-var. There are two primary ways to do this:

    1. Load via require()

    Call require('dotenv').config() at the entry point of your application to populate process.env.

    2. Preload via CLI

    Use the Node.js --require (or -r) flag to load dotenv/config before your script executes. This avoids adding manual configuration code to your source files.

    Pre-requisite: Ensure you have a .env file in your repository containing your variables (e.g., MY_VAR=a-string-value!).

    // Option 1: Load via require()
    require('dotenv').config()
    const env = require('env-var')
    const myVar = env.get('MY_VAR').asString()
  7. Use built-in accessors directly via env.accessors

    master

    The env.accessors object exposes all the parsing and validation logic as standalone functions. These accept a String as their first argument. This is useful for building custom accessors or validating strings manually without using the env.get() chain.

    const env = require('env-var')
    
    // Validate that a string is JSON directly
    const myJsonDirectAccessor = env.accessors.asJson(process.env.SOME_JSON)
  8. Read environment variables with get()

    master

    The get() function has two modes:

    1. Read a specific variable: Pass a string argument (the variable name) to return a variable object for that key.
    2. Read the entire environment: Pass no arguments to return the entire environment object (e.g., process.env).
    const env = require('env-var')
    
    // Read a specific variable
    const limit = env.get('MAX_CONNECTIONS').asIntPositive()
    
    // Returns the entire process.env object
    const allVars = env.get()
  9. Define custom accessors using extraAccessors

    master

    When initializing an env-var instance with from(), you can provide an extraAccessors object. This allows you to attach custom transformation or validation logic to any variable retrieved from that instance.

    Each accessor function must accept at least one argument: value, which is the raw value of the environment variable. Note: Do not assume value is a string.

    Accessors can also accept additional arguments, which must be passed explicitly when the accessor is invoked on a variable.

    const { from } = require('env-var')
    
    process.env.ADMIN = 'admin@example.com'
    
    const env = from(process.env, {
      asEmail: (value, requiredDomain) => {
        const split = String(value).split('@')
        if (split.length !== 2) {
          throw new Error('must contain exactly one "@"')
        }
        if (requiredDomain && (split[1] !== requiredDomain)) {
          throw new Error(`must end with @${requiredDomain}`)
        }
        return value
      }
    })
    
    // Usage without extra parameters
    let validEmail = env.get('ADMIN').asEmail()
    
    // Usage with an additional parameter
    let domainSpecificEmail = env.get('ADMIN').asEmail('example.com')
  10. Initialize env-var with custom values or loggers using from()

    master

    Use from(values, extraAccessors, logger) to create an env-var instance that reads from a provided object instead of the default process.env. This is useful for testing or non-Node.js environments.

    You can also provide a custom logger function to log validation messages. The logger signature is (varname, str), where varname is the variable name and str is the log message.

    const env = require('env-var').from({
      API_BASE_URL: 'https://my.api.com/'
    })
    
    // apiUrl will be 'https://my.api.com/'
    const apiUrl = env.get('API_BASE_URL').asUrlString()