> ## Documentation Index
> Fetch the complete documentation index at: https://docs.gatojs.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Environment variables

> Reference for every environment variable a GatoJS app reads, how @gatojs/env validates them at startup, which are required in production, and how modules add their own.

A GatoJS app validates its environment with Zod before it serves the first request. A missing or malformed variable stops the server with a report that lists every problem. This page covers how validation works and lists every variable, from the core, from kit modules and from outside the schema.

## Quick start

`.env.example` lists every variable the schema knows (except `NODE_ENV`). When you create a project, the CLI copies it to `.env`, generates a random `BETTER_AUTH_SECRET` and fills in `ADMIN_EMAIL` if you gave one.

```bash .env.example theme={null}
DATABASE_URL=postgresql://postgres:postgres@localhost:5432/wa_app
BETTER_AUTH_SECRET=change-me-to-a-random-string-of-at-least-32-chars
APP_URL=http://localhost:3000
RESEND_API_KEY=
SMTP_URL=smtp://localhost:1025
EMAIL_FROM="WA App <noreply@example.com>"
AUTH_PUBLIC_SIGNUP=false
MULTI_ORG=false
ADMIN_IMPERSONATION=false
ADMIN_EMAIL=
ADMIN_PASSWORD=
LOG_LEVEL=info
OTEL_EXPORTER_OTLP_ENDPOINT=

# wa:modules:start
# api-keys
API_KEY_PEPPER=dev-only-api-key-pepper-change-me-0123456789

# uploads
STORAGE_PROVIDER=local
STORAGE_LOCAL_PATH=./volumes/uploads
# ... S3_* variables
# wa:modules:end
```

The block between `# wa:modules:start` and `# wa:modules:end` is generated (see [Module variables](#module-variables)). The placeholder names (`wa_app`, `WA App`) are replaced with your project's names at creation time.

> [!WARNING]
>
> `gato add` updates `.env.example` but **not** `.env`. After adding a module, copy its new variables from the `wa:modules` region into `.env` and set real values, or the server may refuse to start. After `gato remove`, delete them from `.env` and from your production variables.

## How validation works

The env layer is the `@gatojs/env` workspace package (`packages/env`). It exports the core schema `coreEnvSchema` and helpers to check it together with module schemas:

| Export | What it does |
| - | - |
| `checkEnv(source, moduleSchemas)` | Returns `{ ok: true, env }` or `{ ok: false, issues }`. |
| `parseEnv(source, moduleSchemas)` | Returns the parsed env or throws one error listing all issues. |
| `verifyEnvOnStartup(source, io, moduleSchemas)` | The startup check described below. |
| `createEnv(moduleSchemas)` | Returns a lazy `env` object that validates `process.env` on first property access and caches the result. |
| `httpUrl()`, `blankAsUndefined()`, `flag()` | Schema fragments for feature env schemas. |
| `allOrNone(names, label)`, `requiredForProvider(var, value, names)` | Rules for `.superRefine(...)` in feature schemas. |

The generator ties the package to your modules: `src/modules.generated.ts` ends with `export const env = createEnv(moduleEnvSchemas)`. App code imports it from the stable path:

```ts theme={null}
import { env } from "@/env";

if (env.MULTI_ORG) {
  // ...
}
```

### At startup

Next.js calls `register()` in `src/instrumentation.ts` when the server starts. In the Node.js runtime it checks the whole environment, core and installed modules, before anything else:

```ts src/instrumentation.ts theme={null}
const { verifyEnvOnStartup, processStartupIo } = await import("@gatojs/env");
const { moduleEnvSchemas } = await import("@/modules.generated");
verifyEnvOnStartup(process.env, processStartupIo, moduleEnvSchemas);
```

With valid variables it prints nothing. Otherwise it writes a report to stderr and exits with code 1. A standalone server started with no variables at all prints:

```text theme={null}
Nieprawidłowe zmienne środowiskowe (6):
- DATABASE_URL: Invalid input: expected string, received undefined
- BETTER_AUTH_SECRET: Invalid input: expected string, received undefined
- APP_URL: Invalid input: expected string, received undefined
- EMAIL_FROM: Invalid input: expected string, received undefined
- API_KEY_PEPPER: Invalid input: expected string, received undefined
- STORAGE_LOCAL_PATH: wymagana w produkcji przy STORAGE_PROVIDER=local: wskaż trwały katalog
```

The header reads "Invalid environment variables (6)". Messages come from Zod (English) or from the kit's own rules (Polish). The last two lines come from the `api-keys` and `uploads` modules.

Things to know about the report:

* **It goes to the console, not the logger**, so you see it in container logs even without OTLP export.
* **`✓ Ready` doesn't mean the env is valid.** Next.js prints its banner before the report.
* **A bad module variable stops the whole app**, not just that module.
* **Production rules may surface one round at a time.** Zod checks a schema's cross-field refinements (such as "`RESEND_API_KEY` required in production") only after the schema's basic field rules pass. Fixing one batch of errors can reveal the next.

### When there is no startup check

* **`next build`** doesn't call `register()`, so `npm run build` succeeds without a `.env`. `verifyEnvOnStartup` also skips itself when `NEXT_PHASE` is `phase-production-build`.
* **The Edge runtime.** `register()` returns early unless `NEXT_RUNTIME` is `nodejs`.
* **Scripts and tests.** Vitest, `npm run admin:create` and other scripts don't run `register()`; their variables are checked on the first read of `env`.

Because `env` is lazy, importing it never throws. In unit tests, mock the module instead:

```ts theme={null}
vi.mock("@/env", () => ({ env: { MULTI_ORG: false } }));
```

> [!NOTE]
>
> The parsed env is cached for the life of the process. Restart the dev server, or redeploy, after changing a variable.

## Parsing rules

| Kind | Rule |
| - | - |
| **Flag** (`flag()`) | Trimmed and lowercased, then must be empty, `true` or `false`. Empty or missing means `false`. Anything else (`1`, `yes`, `on`) is an **error**, so a typo can't silently switch a mode off. |
| **Optional** (`blankAsUndefined`) | An empty or whitespace-only value counts as unset, so blank lines copied from `.env.example` enable nothing. Other values pass through untrimmed. |
| **HTTP URL** (`httpUrl()`) | Must be a full URL with `http` or `https`. `localhost:4318` is rejected, because plain `z.url()` would read `localhost:` as a protocol. |

## Core variables

These come from `coreEnvSchema` and exist in every project.

| Variable | Type | Default | Production | Description |
| - | - | - | - | - |
| `NODE_ENV` | `development`, `test` or `production` | `development` | Set by `next start`, the standalone server and the Dockerfile | Enables the production rules below. Any other value is an error. |
| `DATABASE_URL` | non-empty string | none | **Required** | PostgreSQL connection string. |
| `BETTER_AUTH_SECRET` | at least 32 characters, ignoring surrounding spaces | none | **Required**; must differ from the `.env.example` value | better-auth secret that signs sessions and tokens. Generate one with `openssl rand -base64 32`. |
| `APP_URL` | HTTP URL | none | **Required** | Public URL of the app. better-auth uses it as `baseURL` and email links are built from it. |
| `EMAIL_FROM` | non-empty string, format not checked | none | **Required** | Sender, for example `Acme <noreply@acme.com>`. |
| `RESEND_API_KEY` | optional | none | **Required**, even when `SMTP_URL` is set | Resend API key. Used only when `SMTP_URL` is empty. |
| `SMTP_URL` | optional, format not checked | none | Leave unset | SMTP URL for nodemailer. Takes precedence over Resend. |
| `AUTH_PUBLIC_SIGNUP` | flag | `false` | Optional | `true` allows sign-up without an invitation. |
| `MULTI_ORG` | flag | `false` | Optional | `true` enables multiple organizations per user. See [Organizations](https://docs.gatojs.com/concepts/organizations.md). |
| `ADMIN_IMPERSONATION` | flag | `false` | Optional | `true` lets a global `admin` impersonate regular users. See [Superadmin and service mode](https://docs.gatojs.com/concepts/superadmin-and-service-mode.md). |
| `ADMIN_EMAIL` | optional | none | Don't set | Default `--email` for `npm run admin:create`. |
| `ADMIN_PASSWORD` | optional | none | Don't set | Default `--password` for `admin:create`. Empty means "generate one". |
| `LOG_LEVEL` | optional, any string | none (`info` in `.env.example`) | Don't set | Accepted but **has no effect**; the logger doesn't filter by level. |
| `OTEL_EXPORTER_OTLP_ENDPOINT` | optional HTTP URL | none | Not enforced, but **set it** | Base URL of an OTLP/HTTP collector, without `/v1/logs`. Without it, production logs are discarded. See [Logging and observability](https://docs.gatojs.com/configuration/logging-and-observability.md). |

> [!WARNING]
>
> In production the schema rejects `BETTER_AUTH_SECRET` (and `API_KEY_PEPPER`) when they still hold the sample value from `.env.example`. Generate fresh values per environment.

## Module variables

A feature can ship `src/features/<name>/env.ts` exporting a Zod `envSchema`. The generator adds it to `moduleEnvSchemas`, and `checkEnv` combines it with the core schema through `z.intersection`. Errors from both end up in the same startup report.

The lines in the `wa:modules` region of `.env.example` come from a different place: the `env` field of each module's manifest in `.wa/kit.json`. The generator doesn't compare the two lists, so a variable checked by `envSchema` may be missing from `.env.example`. The core's own variables are written into `.env.example` outside the region.

> [!NOTE]
>
> `env` is typed as `CoreEnv`, so `env.MY_MODULE_VAR` is a TypeScript error (TS2339) even though the value is present at runtime. The kit has no built-in typed accessor for feature variables yet.

### `api-keys`

| Variable | Rule | Production |
| - | - | - |
| `API_KEY_PEPPER` | At least 32 characters. | **Required**; must not be the `.env.example` value. Changing it invalidates every issued API key, so keep it stable per environment. |

See [API keys](https://docs.gatojs.com/modules/api-keys.md).

### `uploads`

| Variable | Rule | Production |
| - | - | - |
| `STORAGE_PROVIDER` | `local` (default) or `s3`, case-insensitive. Anything else: `dozwolone wartości: local, s3` ("allowed values"). | Optional. |
| `STORAGE_LOCAL_PATH` | Directory for `local`. Defaults to `./volumes/uploads`. | Outside Railway: **required** and **absolute**. On Railway: must lie inside the attached volume, or be left unset. |
| `S3_ENDPOINT` | HTTP URL. | Required when `STORAGE_PROVIDER=s3`. |
| `S3_ACCESS_KEY_ID`, `S3_SECRET_ACCESS_KEY`, `S3_BUCKET` | Non-empty. | Required when `STORAGE_PROVIDER=s3`. |
| `S3_REGION` | Non-empty; default `auto`. | Optional. |
| `S3_FORCE_PATH_STYLE` | `true` or `false`; default `false`. | Optional. |
| `RAILWAY_ENVIRONMENT_ID`, `RAILWAY_VOLUME_MOUNT_PATH` | Set by Railway, read by the schema. | Don't set yourself. |

With `local` in production on Railway, a service without a volume fails with `na Railway bez wolumenu pliki zginą przy redeployu` ("on Railway without a volume files will be lost on redeploy"). See [File storage](https://docs.gatojs.com/deployment/file-storage.md) and [Uploads](https://docs.gatojs.com/modules/uploads.md).

## Variables outside the schema

These are read directly by code, configuration or libraries. They are not in `.env.example` and are not validated.

| Variable | Read by | Default | Description |
| - | - | - | - |
| `DATABASE_POOL_MAX` | `src/shared/lib/prisma.ts` | `10` (also for invalid values) | Maximum connections in the `pg` pool. |
| `OTEL_SERVICE_NAME` | `src/instrumentation.ts` | project slug | `service.name` in exported logs and traces. |
| `GIT_COMMIT_SHA` | `src/instrumentation.ts` | `dev` | `service.version` in exported telemetry. Nothing in the kit sets it. |
| `OTEL_EXPORTER_OTLP_HEADERS`, `OTEL_EXPORTER_OTLP_LOGS_HEADERS` | OpenTelemetry exporter | none | `key=value` pairs, comma-separated, sent to the collector (for example an API key). |
| `PORT` | Next.js | `3000` | Server port. Setting `PORT` in `.env` has no effect on `next dev`; pass it in the shell. |
| `HOSTNAME` | Standalone `server.js` | `0.0.0.0` (Dockerfile) | Listen address. Keep `0.0.0.0` or `::`. See [Docker](https://docs.gatojs.com/deployment/docker.md#runtime-environment). |
| `NEXT_TELEMETRY_DISABLED` | Next.js | `1` in the Dockerfile | Disables Next.js telemetry. |
| `NEXT_RUNTIME`, `NEXT_PHASE` | Set by Next.js | — | Control whether the startup check runs. |
| `DB_PORT`, `MAILPIT_UI_PORT`, `MAILPIT_SMTP_PORT` | `docker-compose.yml`, e2e config | `5432`, `8025`, `1025` | Local Docker ports. Update `DATABASE_URL` and `SMTP_URL` when you change them. |
| `MINIO_PORT`, `MINIO_CONSOLE_PORT` | `docker-compose.yml` (uploads) | `9000`, `9001` | Local MinIO ports for the `s3` profile. |
| `INTEGRATION_DATABASE_URL` | Integration tests | `postgresql://postgres:postgres@localhost:5432/<slug>_test` | Database for integration tests; its name must end in `_test`. |
| `E2E_CORE_PORT`, `E2E_MULTI_ORG_PORT`, `E2E_ADMIN_EMAIL`, `E2E_ADMIN_PASSWORD`, `MAILPIT_URL` | `e2e/env.ts` | see file | End-to-end test servers and fixtures. |
| `CI` | `playwright.config.ts` | none | Enables `forbidOnly` and the HTML report. |

## Variables read without validation

Outside the Next.js server (which always runs the startup check), validation only protects reads through `env`. A few schema variables are read directly from `process.env`:

* `DATABASE_URL` in `src/shared/lib/prisma.ts` and `prisma.config.ts`. Prisma CLI commands such as `migrate deploy` work without the other variables.
* `NODE_ENV` and `OTEL_EXPORTER_OTLP_ENDPOINT` in the logger and `instrumentation.ts`.
* `ADMIN_EMAIL` and `ADMIN_PASSWORD` in `scripts/admin-create.ts`.

## Related

> [card] [Deploy on Railway](https://docs.gatojs.com/deployment/railway.md)
>
> What to set in production, step by step.

> [card] [Logging and observability](https://docs.gatojs.com/configuration/logging-and-observability.md)
>
> OTLP export, the logger and the healthcheck.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.