𝗗𝗲𝗳𝗶𝗻𝗲 𝗢𝗻𝗰𝗲, 𝗧𝗿𝘂𝘀𝘁 𝗘𝘃𝗲𝗿𝘆𝘄𝗵𝗲𝗿𝗲
CtroEnv uses four core validator factories to keep your environment variables safe.
Here is how they work:
string() for text Use this for URLs, emails, and ports. You can chain rules like .min() or .max() to set length limits.
number() for numeric values This converts strings like "3000" into actual numbers. You can enforce integers or positive values.
boolean() for true or false This handles feature flags. It turns "true", "1", or "false" into actual booleans.
pick() for specific sets Use this to restrict values to a list. For example, you can force NODE_ENV to only be "development", "staging", or "production". If you make a typo, the error suggests the correct spelling.
Useful tools for every validator:
• .default(value) - Sets a fallback if the variable is missing. • .optional() - Allows the variable to be undefined. • .secret() - Masks sensitive data in your logs. • .describe(text) - Adds documentation for your error messages. • .validate(fn) - Lets you write custom logic for one-off rules.
CtroEnv works across different environments:
- Node.js: Use nodeSource() or loadEnv() to read .env files.
- Vite: Use the vitePlugin to fail your build if variables are invalid.
- Next.js: Use the built-in support to separate server and client variables. This stops you from accidentally exposing secrets to the browser.
When validation fails, CtroEnv does not just stop. It collects every single error and shows them all at once. You get a clear list of what is missing, what has the wrong type, and what failed your custom rules.
This keeps your configuration immutable and your runtime predictable.
Source: https://dev.to/ctrotech/define-once-trust-everywhere-ctroenv-deep-dive-3bjl