EnvManager - sebamar88/bytekit GitHub Wiki
🌍 EnvManager
EN: Isomorphic environment variable reader. Reads from
process.envin Node.js andimport.meta.envin browsers (Vite, etc.). Simple — just 3 methods.ES: Lector isomórfico de variables de entorno. Lee de
process.enven Node.js eimport.meta.enven navegadores (Vite, etc.). Simple — solo 3 métodos.
📦 Import
import { EnvManager } from "bytekit/env-manager";
// or | o también:
import { EnvManager } from "bytekit";
⚙️ Constructor
const env = new EnvManager();
EN: No arguments needed. EnvManager auto-detects the runtime (Node.js vs browser) and reads from the appropriate source.
ES: No necesita argumentos. EnvManager detecta automáticamente el entorno (Node.js vs navegador) y lee de la fuente apropiada.
📋 Methods / Métodos
| Method / Método | Signature / Firma | Description (EN) | Descripción (ES) |
|---|---|---|---|
get |
get(name: string): string | undefined |
Returns the variable value, or undefined if not set |
Devuelve el valor de la variable, o undefined si no existe |
require |
require(name: string): string |
Returns the value or throws if missing | Devuelve el valor o lanza un error si falta |
isProd |
isProd(): boolean |
Returns true if NODE_ENV or MODE is "production" |
Devuelve true si NODE_ENV o MODE es "production" |
🧠 How It Works / Cómo Funciona
EN: EnvManager checks at construction time whether
windowexists. In Node.js, it reads fromprocess.env. In the browser, it reads fromimport.meta.env(standard in Vite, Astro, SvelteKit, etc.). TheisProd()method checks bothNODE_ENVandMODEto work correctly in either environment.ES: EnvManager verifica en el momento de construcción si
windowexiste. En Node.js, lee deprocess.env. En el navegador, lee deimport.meta.env(estándar en Vite, Astro, SvelteKit, etc.). El métodoisProd()revisa tantoNODE_ENVcomoMODEpara funcionar correctamente en ambos entornos.
┌──────────┐ ┌──────────────────────┐
│ Node.js │ ──────▶│ process.env │
└──────────┘ └──────────────────────┘
┌──────────┐ ┌──────────────────────┐
│ Browser │ ──────▶│ import.meta.env │
│ (Vite) │ └──────────────────────┘
└──────────┘
💡 Examples / Ejemplos
Basic Usage / Uso Básico
import { EnvManager } from "bytekit/env-manager";
const env = new EnvManager();
// EN: Read an optional variable
// ES: Leer una variable opcional
const apiUrl = env.get("API_URL");
console.log(apiUrl); // "https://api.example.com" or undefined
Required Variable / Variable Obligatoria
const env = new EnvManager();
// EN: Throws if DATABASE_URL is not set — fail fast
// ES: Lanza error si DATABASE_URL no está definida — falla rápido
const dbUrl = env.require("DATABASE_URL");
// Error: "Missing environment variable: DATABASE_URL"
Environment Detection / Detección de Entorno
const env = new EnvManager();
if (env.isProd()) {
// EN: Production-only logic
// ES: Lógica solo para producción
enableAnalytics();
disableDebugLogs();
} else {
// EN: Development mode
// ES: Modo desarrollo
enableDevTools();
}
Configuration Pattern / Patrón de Configuración
import { EnvManager } from "bytekit/env-manager";
import { ApiClient } from "bytekit/api-client";
const env = new EnvManager();
const client = new ApiClient({
baseUrl: env.require("VITE_API_URL"),
defaultHeaders: {
Authorization: `Bearer ${env.require("VITE_API_TOKEN")}`,
},
});
Safe Fallback / Valor por Defecto Seguro
const env = new EnvManager();
// EN: Use get() with a fallback for optional config
// ES: Usa get() con un valor por defecto para configuración opcional
const port = env.get("PORT") ?? "3000";
const logLevel = env.get("LOG_LEVEL") ?? "info";
⚠️ Important Notes / Notas Importantes
EN: In browser environments (Vite), only variables prefixed with
VITE_are exposed to client-side code. This is a Vite security feature, not a bytekit limitation.ES: En entornos de navegador (Vite), solo las variables con prefijo
VITE_se exponen al código del cliente. Esta es una característica de seguridad de Vite, no una limitación de bytekit.
EN:
EnvManageris an instance-based class (not static). Create an instance withnew EnvManager().ES:
EnvManageres una clase basada en instancias (no estática). Crea una instancia connew EnvManager().