Env Configuration
Environment variables are a critical part of any production application. They allow you to configure your application based on the environment it's running in (development, testing, production).
To ensure your application has all the required environment variables with the correct types, we recommend using Zod for schema validation and Dotenv for loading variables from a .env file.
Features
- Type Safety: Automatic TypeScript types for your environment variables.
- Fail Fast: The application will not start if any required environment variable is missing or invalid.
- Centralized Access: Access all environment variables through a single, validated
envobject. - Default Values: Easily provide default values for optional environment variables.
Installation Guide
Install the component using the ServerCN CLI:
npx servercn-cli add env-configBasic Implementation
Create a file named src/configs/env.ts (or similar) and add the following code:
Usage
You can now import the env object anywhere in your application and get full type safety and auto-completion.
Why Zod?
Using Zod for environment validation provides several benefits:
- Validation: It ensures that environment variables like PORT are actually strings/numbers as expected.
- Transformation: You can transform strings into other types (e.g., parsing a string to a boolean or number).
- Error Reporting: If an environment variable is missing or wrong, Zod provides detailed error messages.
Example .env file
Make sure to create a .env file in your root directory: