𝗗𝗲𝗳𝗶𝗻𝗲 𝗢𝗻𝗰𝗲, 𝗧𝗿𝘂𝘀𝘁 𝗘𝘃𝗲𝗿𝘆𝘄𝗵𝗲𝗿𝗲: 𝗖𝘁𝗿𝗼𝗘𝗻𝘃 𝗗𝗲𝗲𝗽 𝗗𝗶𝘃𝗲
The CtroEnv core API uses four validator factories. You can use them to secure your environment variables with ease.
Here is how they work:
• string() — Use this for text. You can add rules for URLs, emails, ports, or specific lengths. It supports regex for custom patterns.
• number() — Use this for numeric values. It converts strings like "3000" into actual numbers. You can enforce integers, positive values, or specific ranges.
• boolean() — Use this for true/false values. It handles strings like "true" or numbers like "1" automatically. This is perfect for feature flags.
• pick() — Use this to restrict values to a specific list. It creates literal types so your code knows exactly which strings are allowed. It even suggests corrections if you make a typo.
Useful methods for every validator:
- .default(value) — Sets a fallback if the variable is missing.
- .optional() — Allows the value to be undefined.
- .describe(text) — Adds documentation for your error messages and docs.
- .secret() — Masks sensitive values in your terminal output.
- .validate(fn) — Lets you write custom logic for one-off rules.
CtroEnv works across different environments:
- Node.js: Use nodeSource() or loadEnv() to read process.env or .env files.
- Vite: Use the vite plugin to fail your build if variables are invalid.
- Next.js: Use the built-in support to separate server and client variables. This prevents you from accidentally leaking 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 report with the key, the message, and even suggestions on how to fix it.
The final output is a frozen object. This means your configuration is read-only and safe from accidental changes during runtime.
Source: https://dev.to/ctrotech/define-once-trust-everywhere-ctroenv-deep-dive-3bjl