Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
2 tasks done
garysassano opened this issue Oct 5, 2024 · 1 comment
Open
2 tasks done
Labels
feature-request This item refers to a feature request for an existing or new utility need-customer-feedback Requires more customers feedback before making or revisiting a decision

Comments

@garysassano
Copy link
Contributor

garysassano commented Oct 5, 2024

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.

@garysassano garysassano added feature-request This item refers to a feature request for an existing or new utility triage This item has not been triaged by a maintainer, please wait labels Oct 5, 2024
@am29d
Copy link
Contributor

am29d commented Oct 7, 2024

Hey @garysassano , thanks for raising the issue. This is a common use case where you'd spend few lines of code to fetch and validate the environment variables that we could simplify and provide better error handling, especially for higher number of variables (10+).

The requirements and the solution remind me of https://github.com/ran-isenberg/aws-lambda-env-modeler from @ran-isenberg. Instead of calling getRequiredEnvVar multiple times, I see a better solution in having an environment object defined as a model. We could use zod parser to validate the model and also get a full error report for all environment variables.

const envSchema = z.object({
  DB_NAME: z.string(),
  DB_PORT: z.number(),
})

type MyEnvs = z.infer<typeof envSchema>;

const myEnvs: Myenvs = validateEnvs(envSchema)

const handler = async (event: unknown, context: Context) => {
  // myEnvs is available, valid and typed here
}

The main benefit we could provide is 1/ fetch a list of variables from process.env, 2/ validate against pre-defined schema 3/ output full report on all variables.

I'd like to hear more feedback from the community and customers how they approach this problem and if it's worth implementing.

@am29d am29d added need-customer-feedback Requires more customers feedback before making or revisiting a decision and removed triage This item has not been triaged by a maintainer, please wait labels Oct 7, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature-request This item refers to a feature request for an existing or new utility need-customer-feedback Requires more customers feedback before making or revisiting a decision
Projects
Development

No branches or pull requests

2 participants