EnvManager - sebamar88/bytekit GitHub Wiki

🌍 EnvManager

EN: Isomorphic environment variable reader. Reads from process.env in Node.js and import.meta.env in browsers (Vite, etc.). Simple — just 3 methods.

ES: Lector isomórfico de variables de entorno. Lee de process.env en Node.js e import.meta.env en 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 window exists. In Node.js, it reads from process.env. In the browser, it reads from import.meta.env (standard in Vite, Astro, SvelteKit, etc.). The isProd() method checks both NODE_ENV and MODE to work correctly in either environment.

ES: EnvManager verifica en el momento de construcción si window existe. En Node.js, lee de process.env. En el navegador, lee de import.meta.env (estándar en Vite, Astro, SvelteKit, etc.). El método isProd() revisa tanto NODE_ENV como MODE para 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: EnvManager is an instance-based class (not static). Create an instance with new EnvManager().

ES: EnvManager es una clase basada en instancias (no estática). Crea una instancia con new EnvManager().


🔗 See Also / Véase También

  • Logger — Adjusts default log level based on environment / Ajusta el nivel de log por defecto según el entorno
  • ApiClient — HTTP client that can be configured with env variables / Cliente HTTP configurable con variables de entorno