Skip to Content
Server

Env

Workers-safe environment access and lazy, validated config.

Usage

import { z } from "zod"
import { createEnv, initRuntimeEnv } from "@dapplelight/signet-server/env"
import { app } from "./app"

export const env = createEnv(
  z.object({ DATABASE_URL: z.string().url(), SENTRY_DSN: z.string().url().optional() }),
  { optionalFeatures: [["SENTRY_DSN", "error reporting"]] },
)

export default {
  fetch(req: Request, bindings: Record<string, unknown>, ctx: ExecutionContext) {
    initRuntimeEnv(bindings) // first thing: Workers pass secrets here, not process.env
    return app.fetch(req, bindings, ctx)
  },
}

createEnv validates on first property access, not at import. A deploy-time module load with no secrets does not fail.

API

ExportWhat it does
initRuntimeEnv(env)Store the bindings a Worker receives.
getRuntimeEnv()Injected bindings merged over process.env; injected wins.
resetRuntimeEnv()Clear the injected bindings (tests).
createEnv(schema, options)A Zod-validated env object, checked on first access.
CreateEnvOptionsOptions type.

createEnv(schema, options)

OptionTypeDefault
optionalFeatures[key, feature][]noneOptional vars whose absence disables a feature. Warned once.
warn(message) => voidstderrWhere warnings go.
source() => Record<string, string | undefined>getRuntimeEnvOverride the source.

An invalid env throws Invalid environment variables: with one line per bad path.

Examples

Test with a fixed source

import { z } from "zod"
import { createEnv } from "@dapplelight/signet-server/env"

const schema = z.object({ DATABASE_URL: z.string().url() })

const env = createEnv(schema, { source: () => ({ DATABASE_URL: "postgres://localhost/test" }) })