Skip to content

Environment variables

Your app reads configuration, such as database URLs and API keys, from environment variables. Kiln loads .env files for you, and gives you defineEnv to check that the variables you need are present and have the right type.

Environment files

The CLI loads these files, in this order, with Vite's rules. For each command, a real environment variable always wins over a file value:

CommandFiles loaded
kiln dev, kiln test.env, .env.local, .env.development, .env.development.local
kiln build, kiln start.env, .env.local, .env.production, .env.production.local

A .local file is meant for values that should not be committed, such as secrets on your own machine. Add .env.local to .gitignore.

bash
# .env
APP_NAME=My app
PORT=3000

# .env.local
DATABASE_URL=postgres://localhost/dev

Schemas with defineEnv

defineEnv reads the variables you name and returns typed values. Write it in one module, and import the result everywhere else:

ts
// app/lib/env.ts
import { defineEnv } from "@kiln-js/core";

export const env = defineEnv({
  APP_NAME: "string",
  PORT: { type: "number", default: 3000 },
  DEBUG: { type: "boolean", default: false },
  DATABASE_URL: "string",
});

Each field is either a type name, which makes the variable required, or an object with a type and a default, which makes it optional.

After the call:

  • env.PORT is a number.
  • env.DEBUG is a boolean.
  • env.DATABASE_URL is a string.

Error reporting

defineEnv checks every field and throws one error that lists all the problems, not just the first:

text
Invalid environment:
  - DATABASE_URL is required
  - PORT must be a number, got "abc"

Start the app after fixing the list. Because the check runs when the module loads, a missing variable stops the server at startup, not on the first request that needs it.

Parsing rules

  • An empty value counts as missing.
  • number accepts anything Number() accepts. "abc" is rejected.
  • boolean is true for 1, true, yes, and on, in any letter case. Any other value is false.
  • string is taken as written.

Where variables are visible

Environment variables are available to server code only. The client bundle does not include them. Read them in loaders, actions, API routes, and .server modules.

A value that a browser needs must come from a loader, or be passed as a prop. Do not put secrets in a loader's return value.

The doctor check

kiln doctor checks DATABASE_URL when your app source uses it. It warns when the variable is used in code but not defined in .env or .env.local.

Tests

Pass a plain object as the second argument to defineEnv to test a schema without changing process.env:

ts
import { defineEnv } from "@kiln-js/core";

const env = defineEnv({ PORT: { type: "number", default: 3000 } }, { PORT: "8080" });
// env.PORT === 8080