Config and environment
How the Naalya API validates its environment at boot with Zod and reads config at runtime through ConfigService.
Use this page to look up how the API gets its settings: where each variable is declared, what happens at boot, how code reads a value, and which section holds it. To add or rotate a value, follow Adding and rotating.
libs/shared/src/config/env.config.ts is the single source of truth for API configuration. It validates process.env against a Zod schema at boot and returns a nested config object. Application code reads that object through ConfigService, not process.env.
env.config.ts
The file exports these names.
| Export | What it is |
|---|---|
envSchema | The Zod schema for the flat environment. A missing required variable fails the parse. |
config() | Runs envSchema.parse(process.env) and returns the nested config object, grouped by section (auth, database, email, and so on). |
EnvTypes | ReturnType<typeof config>: the type of the nested object. Use it as ConfigService<EnvTypes>. |
SharedEnv | z.infer<typeof envSchema>: the raw, flat environment shape. Rarely needed. |
The clinic app does not use these. It validates ehrEnvSchema, loads ehrConfig(), and reads only EHR_* plus the logging and docs variables.
Boot validation
config() wraps any Zod failure in an error with a fixed prefix. The app does not start.
const config = () => {
try {
envSchema.parse(process.env);
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
throw new Error(`Config validation error: ${errorMessage}`);
}
return {
/* ...nested config object... */
};
};The message after Config validation error: names each variable that failed and why.
A boot failure is a config failure first
A fresh clone, a new machine, or a newly required variable all fail here. Compare .env.local with envSchema before you read the source.
Loading
Each app loads its config through Nest's ConfigModule.forRoot. The server, worker, and audit apps load the shared config. The clinic app loads ehrConfig().
ConfigModule.forRoot({
isGlobal: true,
load: [config],
envFilePath: '.env.local',
}),| Option | Effect |
|---|---|
load: [config] | Runs the Zod check and builds the nested object. |
isGlobal: true | Any module can inject ConfigService without importing ConfigModule. |
envFilePath: '.env.local' | The dotenv file Nest reads on a developer machine. |
Reading a value
Inject ConfigService and read with a dot-notation key that mirrors the nested object, such as auth.jwtSecret, email.fromEmail, or frontend.allowedOrigins. Do not read process.env in application code.
| Method | Returns | Use when |
|---|---|---|
get('section.key', { infer: true }) | The value, or undefined. { infer: true } narrows the return type. | The value has a fallback or the feature is optional. |
getOrThrow('section.key') | The value, or throws with the key name. | The caller cannot work without it, such as a signing secret or connection string. |
Example: CORS origins are mandatory, so main.ts uses getOrThrow.
const configService = app.get(ConfigService);
app.enableCors({
origin: configService.getOrThrow<string[]>('frontend.allowedOrigins'),
credentials: true,
});Config sections
The nested object groups variables by what they power. Every variable, with its default, is on Environment variables.
| Section | Powers | Example keys |
|---|---|---|
| (root) | The HTTP server | port, host, nodeEnv |
frontend | CORS and redirect origins | url, allowedOrigins |
database | The Postgres connection | url, poolSize |
auth | JWTs, impersonation, admin allowlists | jwtSecret, jwtExpiresIn, superAdminEmails |
otp | One-time password rules | expiryMinutes, resendCooldownSeconds, maxAttempts |
email | Transactional email through Resend | resendApiKey, fromEmail, fromName |
microsoft | Microsoft 365 OAuth and directory sync | clientId, clientSecret, tenantId, webhookSecret |
cloudflare | R2 object storage and AI search | accountId, r2AccessKeyId, baseUrl, aiSearchApiToken |
openai | OpenAI calls, including Rover's chat, small talk, slide reader, and illustrations | apiKey, model, microModel, imageModel |
unipile | Website enquiry messaging | apiKey, baseUrl, webhookSecret |
rabbitmq, redis | Microservice transport and BullMQ queues | url |
docs | HTTP Basic Auth on /docs* | username, password |
Value formats and defaults
| Variable or key | Format | Default |
|---|---|---|
FRONTEND_URL | Comma-separated string. frontend.allowedOrigins is the full array and drives CORS. frontend.url is the first entry. | See env.config.ts |
SUPERADMIN_EMAILS | Comma-separated string. Optional in the schema. | See env.config.ts |
auth.jwtExpiresIn and other token lifetimes | Milliseconds as a string. Parse where used. | '900000' (15 minutes) for jwtExpiresIn |
redis.url | URL | redis://localhost:6379 |
openai.model | Model name. Rover sends this value as it is | gpt-5.2 |
otp.expiryMinutes | Minutes | 15 |
DATABASE_POOL_SIZE | Coerced to a positive integer. Exposed as database.poolSize; DatabaseModule passes it to TypeORM poolSize. | 30 |
DATABASE_POOL_SIZE is the number of connections per running copy of each app. The schema comment says the number of copies times this value must fit the database's connection limit. See Several copies.
Rover chat models
main is 6bfb9f6bdb004fd3a909405c2c826cf1e383249b (merge of PR #677, 25 November 2026, 04:29 GMT). It shares tree c02ff4560f9a809a1a213073f5651c40eba7b25f with staging 0d611c966e84961c64e909ab50f424a0f2510b6f (PR #676). Compare d229592a...6bfb9f6b is 78 files, 3177 additions and 901 deletions. It does not touch the calendar routes, env.config.ts, .env.example, or APP.secrets. This is on main. Deployment was not verified. No host was checked.
apps/worker/src/naalya-agent/core/supervisor.agent.ts at that commit builds the main chat, small talk, and the slide reader with openai.apiKey and the model name as it is. There is no openai/ prefix and no openrouter section. A search of this tree finds no OPENROUTER_API_KEY. completeOutputFetch and ReasoningRetryMiddleware are not in the 78-file compare. Illustrations use the same key and openai.imageModel.
| Client | Name it sends | Key | Retries |
|---|---|---|---|
| Main chat | openai.model | OPENAI_API_KEY | 8 |
| Small talk | openai.microModel | OPENAI_API_KEY | 0 |
Slide reader, used by check_slide | openai.model | OPENAI_API_KEY | Not set on this constructor |
| Illustrations | openai.imageModel | OPENAI_API_KEY | Not set on this client |
The main-chat comment says a rate-limited call waits and tries again, doubling the wait each time, four to eight minutes in all. That schedule was not measured. Small talk does not retry. The slide reader sets no maxRetries.
The same constructor was re-read on the API default branch, staging ed0e56f87083d7d10466b61b97948f7e855c1c03. The four clients, the retry numbers, and the absence of OPENROUTER_API_KEY are unchanged. supervisor.agent.ts is not in compare 6bfb9f6b...d0fbb403 (23 files) or d0fbb403...ed0e56f8 (36 files). API main is still d0fbb403. Deployment was not verified.
main 8e9ff08f (PR #672) sent those three clients to OpenRouter, required OPENROUTER_API_KEY, and added completeOutputFetch and ReasoningRetryMiddleware. PR #674 reverts that. It is no longer what main does. The PR description for #673 reports a hand rollback of the production worker. That was not verified.
ROVER_JOB_CONCURRENCY defaults to 5. .railway/environments.ts sets roverJobsPerWorker to 100 on staging and 50 on production. That file and RoverJobProcessor were re-read at default branch staging ed0e56f8: the processor reads process.env.ROVER_JOB_CONCURRENCY when the file loads, because the decorator options are fixed then, and uses 5 when the value is missing or not a number. .railway/railway.ts writes that setting onto the worker. It was not re-opened. GitHub Actions run 45252018549 finished apply-production: Plan and Apply both succeeded, and apply-staging was skipped. The logs were not opened. That is not a reading of the live variable, and it is not proof a worker is running this code.
Pip, prefills, the website assistant, Teams Rover, school reports, and embeddings were not opened. No request was sent. Put a development key only in .env.local. Do not commit it.
Variables outside the config object
These are required by envSchema, so the app does not boot without them, but code reads them from process.env where they are used. They are not on the nested object.
AI_GATEWAY_API_KEYAI_GATEWAY_BASE_URL
envSchema is the complete list of what boot requires. The nested object covers only what code reads through ConfigService.
Payment credentials are per school, not environment variables
SchoolPay and other payment provider secrets are not in this file. Each school configures its own provider, stored in the database (SchoolConfigEntity, school_config table). Environment config holds only what the whole deployment shares.
Environment files
Every environment uses the same variable names with different values.
| File | Used for |
|---|---|
.env.example | Committed template. Task env copies it to .env.local when that file does not exist. |
.env.local | Local development. Loaded by the apps and the migration CLI. Not committed. |
.env.staging | The staging deployment |
.env.production | Production |
PORT=3000
HOST=0.0.0.0
NODE_ENV=development
DATABASE_URL=postgres://user:pass@localhost:5432/naalya
JWT_SECRET_KEY=your-signing-secret
# ...every other required key from envSchema....env.example and the schema
Where .env.example and envSchema disagree, envSchema wins.
- A blank value is an empty string. It overrides a Zod
.default(). - An empty string passes a plain
z.string()check, so most keys only have to be present to boot. The file's header says every blank key is required. - A blank value fails boot only where the schema asks for more than a string, such as
R2_PUBLIC_BASE_URL(z.url()). Otherwise the service behind the empty key fails when it is used. SUPERADMIN_EMAILSis missing from.env.example. Add it to.env.localto sign in. See Getting started.
Where to go next
Adding and rotating
Add a new variable to the schema and the config object, set it in Railway, and rotate a secret.
Getting started
Stand up the project locally and build your first .env.local.
Architecture
How the server, worker, and audit apps fit together, and why each loads config.
Auth and permissions
Where the auth, JWT, and OTP config sections are used.
Queues and messaging
How the redis and rabbitmq sections wire up BullMQ and the microservice transport.