Documentation menuMenu da documentação

$ cat docs/env.md

Validated environmentAmbiente validado

Declare variables, secrets and bindings once. If anything is missing in production, the app does not start.Declare variáveis, segredos e bindings uma vez. Se faltar algo em produção, o app não sobe.

DeclareDeclarar

terminal
npm install @tupik/env
env.ts
import { binding, defineEnv, number, oneOf, secret, url, type InferEnv } from '@tupik/env';

export const env = defineEnv({
  JWT_SECRET: secret({ minLength: 32 }),
  DB: binding.d1<D1Database>(),
  CACHE: binding.kv<KVNamespace>(),
  PUBLIC_URL: url(),
  MODE: oneOf(['development', 'production']),
  PORT: number({ integer: true, default: 3000 }),
});

export type Vars = InferEnv<typeof env>;

Zero dependencies and no node:* imports. D1Database and KVNamespace come from @cloudflare/workers-types; without them, binding.d1() types the binding by its shape.

Zero dependências e sem imports node:*. D1Database e KVNamespace vêm do @cloudflare/workers-types; sem eles, binding.d1() tipa o binding pelo formato.

Node.js, Bun and DenoNode.js, Bun e Deno

Call parse() before serve. It reads process.env, Bun.env or Deno.env; serve itself does not change.

Chame parse() antes do serve. Ele lê process.env, Bun.env ou Deno.env; o serve não muda.

server.ts
import { serve } from '@tupik/node';
import { env } from './env';

const vars = env.parse(); // throws one EnvError listing every problem
serve(app, { port: vars.PORT });
import { serve } from '@tupik/node';
import { env } from './env';

const vars = env.parse(); // lança um EnvError com todos os problemas
serve(app, { port: vars.PORT });

Cloudflare WorkersCloudflare Workers

worker.ts
import { createModule } from '@tupik/core';
import { getEnv } from '@tupik/edge';
import { withEnv } from '@tupik/env';
import { env, type Vars } from './env';

const health = createModule().get('/health', {
  access: 'public',
  handler: (ctx) => ({ mode: getEnv<Vars>(ctx).MODE }),
});

export default {
  fetch: withEnv(env, (request, vars, ctx: ExecutionContext) => app.fetch(request, vars, ctx)),
};

The env is validated once per isolate, on the first request. If it is invalid, the problems are logged once and every request gets a generic 500 application/problem+json: the app never runs half configured. Handlers read the typed values with getEnv<Vars>(ctx) from @tupik/edge (the raw ctx.runtime.env is unknown).

O ambiente é validado uma vez por isolate, na primeira requisição. Se estiver inválido, os problemas vão para o log uma vez e toda requisição recebe um 500 application/problem+json genérico: o app nunca roda meio configurado. Os handlers leem os valores tipados com getEnv<Vars>(ctx) do @tupik/edge (o ctx.runtime.env cru é unknown).

What is checkedO que é conferido

  • Builders: string({ minLength, pattern }), secret({ minLength }), url({ protocols }) (default http and https), number({ integer, min, max }), boolean() (true/false, 1/0, yes/no, on/off), oneOf([...]). All take optional and default; secret has no default on purpose. An empty string counts as missing.
  • Any Standard Schema (Zod, Valibot, ArkType) works per variable, as long as it validates synchronously.
  • Bindings by shape: binding.d1() (prepare, batch), kv() (get, put, delete), r2() (get, put, head), queue() (send, sendBatch), durableObject() (idFromName, get), rateLimit() (limit), service() (fetch).
  • All problems at once: one EnvError with issues: [{ key, message }]. Messages never contain the values. safeParse() returns the result instead of throwing.
  • Construtores: string({ minLength, pattern }), secret({ minLength }), url({ protocols }) (padrão http e https), number({ integer, min, max }), boolean() (true/false, 1/0, yes/no, on/off), oneOf([...]). Todos aceitam optional e default; secret não tem default, de propósito. Texto vazio conta como ausente.
  • Qualquer Standard Schema (Zod, Valibot, ArkType) serve por variável, desde que valide de forma síncrona.
  • Bindings pelo formato: binding.d1() (prepare, batch), kv() (get, put, delete), r2() (get, put, head), queue() (send, sendBatch), durableObject() (idFromName, get), rateLimit() (limit), service() (fetch).
  • Todos os problemas de uma vez: um EnvError com issues: [{ key, message }]. As mensagens nunca trazem os valores. O safeParse() devolve o resultado em vez de lançar.

Types and leaksTipos e vazamentos

Values are inferred: vars.JWT_SECRET is string, vars.MODE is 'development' | 'production', and InferEnv<typeof env> names the whole object. The parsed object is frozen. JSON.stringify(vars) and console.log(vars) show secrets as '[redacted]' and bindings as '[binding]'.

Os tipos são inferidos: vars.JWT_SECRET é string, vars.MODE é 'development' | 'production', e InferEnv<typeof env> nomeia o objeto inteiro. O objeto é congelado. JSON.stringify(vars) e console.log(vars) mostram segredos como '[redacted]' e bindings como '[binding]'.