Skip to content

Feature request: Helper function for validating required environment variables #3159

Open
@garysassano

Description

@garysassano

Use case

It would be helpful to have a helper function to validate that required environment variables are present and not empty. This is a common use case when developing Lambda functions, and currently requires developers to write repetitive boilerplate code. This will improve error handling and make code more robust and maintainable.

Solution/User Experience

Create a helper function getRequiredEnvVar that:

  1. Takes the name of an environment variable as a parameter
  2. Checks if the variable exists and is not empty
  3. Returns the value if it exists
  4. Throws a descriptive error if the variable is missing or empty

Example Usage

import { getRequiredEnvVar } from '@aws-lambda-powertools/commons';

// Simple usage
const dbName = getRequiredEnvVar("DB_NAME");

// With type safety
const port = getRequiredEnvVar<number>("PORT", { parser: Number });

// Multiple variables for database configuration
const credentials = {
    username: getRequiredEnvVar("DB_USER"),
    password: getRequiredEnvVar("DB_PASS"),
    host: getRequiredEnvVar("DB_HOST"),
    port: getRequiredEnvVar<number>("DB_PORT", { parser: Number })
};

// Using with custom error message
const apiKey = getRequiredEnvVar("API_KEY", {
    errorMessage: "API_KEY is required for external service integration"
});

Benefits

  • Reduces boilerplate code
  • Provides consistent error handling across applications
  • Improves code readability
  • Makes environment configuration issues more obvious during testing/deployment
  • Follows the "fail fast" principle by validating configuration early
  • Provides type safety and IntelliSense support in TypeScript projects

Implementation Notes

  • Should be added to the @aws-lambda-powertools/commons package
  • Type definition should support generic type parameter for type safety:
interface GetEnvVarOptions<T> {
    parser?: (value: string) => T;
    errorMessage?: string;
}

function getRequiredEnvVar<T = string>(
    name: string, 
    options?: GetEnvVarOptions<T>
): T;
  • Should throw a custom error type (e.g., MissingEnvironmentVariableError) for better error handling
  • Should trim whitespace from values before validation
  • Empty strings should be considered invalid by default
  • Consider adding validation for common types:
    • Numbers (integers, floats)
    • Booleans (true/false, yes/no, 1/0)
    • JSON strings that need parsing
  • Error messages should be clear and actionable, including:
    • The name of the missing/invalid variable
    • The expected format (if a parser was provided)
    • Any custom error message provided in options

Alternative solutions

No response

Acknowledgment

Future readers

Please react with 👍 and your use case to help us understand customer demand.

Metadata

Metadata

Assignees

No one assigned

    Labels

    discussingThe issue needs to be discussed, elaborated, or refinedfeature-requestThis item refers to a feature request for an existing or new utilityneed-customer-feedbackRequires more customers feedback before making or revisiting a decision

    Type

    No type

    Projects

    Status

    Ideas

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions