Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

The method for creating a loader for environment variables that ensures type safety involves the following steps:

  1. Define the list of environment variables that need to be loaded and their corresponding data types.
  2. Use a library or framework that supports type checking and validation of environment variables, such as dotenv or joi.
  3. Implement a function that loads the environment variables and performs type checking and validation using the chosen library or framework.
  4. Use the loaded environment variables in your application, ensuring that their types match the expected types.

Here is an example code snippet in Node.js using dotenv and joi libraries:

const dotenv = require('dotenv');
const Joi = require('joi');

dotenv.config();

const envVarsSchema = Joi.object({
  NODE_ENV: Joi.string()
    .valid('development', 'production', 'test', 'provision')
    .required(),
  PORT: Joi.number()
    .default(3000),
  API_KEY: Joi.string()
    .required()
}).unknown(true);

const { error, value: envVars } = envVarsSchema.validate(process.env);

if (error) {
  throw new Error(`Config validation error: ${error.message}`);
}

module.exports = {
  env: envVars.NODE_ENV,
  port: envVars.PORT,
  apiKey: envVars.API_KEY,
};

In this example, we define a schema for our environment variables using Joi, which specifies the expected data types and validates the values. We then load the environment variables using dotenv and validate them using Joi's validate() method. If there is an error, an exception is thrown. Otherwise, we export the validated environment variables.