Last active
September 5, 2024 21:11
-
-
Save nicolaymh/0e0316785dcf1b4f2eef918a34bb4c99 to your computer and use it in GitHub Desktop.
Common setup for validating environment variables with Joi and TypeScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dotenv/config'; // Load environment variables from a .env file | |
import * as joi from 'joi'; // Import Joi for schema validation | |
// Define an interface for type safety | |
interface EnvVars { | |
PORT: number; | |
} | |
// Define the validation schema for environment variables | |
const envsSchema = joi.object({ | |
PORT: joi.number().required() // PORT must be a number and is required | |
}) | |
.unknown(true); // Allow unknown environment variables | |
// Validate the environment variables against the schema | |
const { error, value } = envsSchema.validate( process.env ); | |
// Throw an error if validation fails | |
if ( error ) { | |
throw new Error(`Config validation error: ${ error.message }`); | |
} | |
// Cast validated values to the EnvVars interface | |
const envVars: EnvVars = value; | |
// Export the validated and typed environment variables | |
export const envs = { | |
port: envVars.PORT, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment