Naalya Handbook

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.

ExportWhat it is
envSchemaThe 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).
EnvTypesReturnType<typeof config>: the type of the nested object. Use it as ConfigService<EnvTypes>.
SharedEnvz.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.

libs/shared/src/config/env.config.ts
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().

apps/server/src/app/app.module.ts
ConfigModule.forRoot({
  isGlobal: true,
  load: [config],
  envFilePath: '.env.local',
}),
OptionEffect
load: [config]Runs the Zod check and builds the nested object.
isGlobal: trueAny 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.

MethodReturnsUse 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.

apps/server/src/main.ts
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.

SectionPowersExample keys
(root)The HTTP serverport, host, nodeEnv
frontendCORS and redirect originsurl, allowedOrigins
databaseThe Postgres connectionurl, poolSize
authJWTs, impersonation, admin allowlistsjwtSecret, jwtExpiresIn, superAdminEmails
otpOne-time password rulesexpiryMinutes, resendCooldownSeconds, maxAttempts
emailTransactional email through ResendresendApiKey, fromEmail, fromName
microsoftMicrosoft 365 OAuth and directory syncclientId, clientSecret, tenantId, webhookSecret
cloudflareR2 object storage and AI searchaccountId, r2AccessKeyId, baseUrl, aiSearchApiToken
openaiOpenAI calls, including Rover's chat, small talk, slide reader, and illustrationsapiKey, model, microModel, imageModel
unipileWebsite enquiry messagingapiKey, baseUrl, webhookSecret
rabbitmq, redisMicroservice transport and BullMQ queuesurl
docsHTTP Basic Auth on /docs*username, password

Value formats and defaults

Variable or keyFormatDefault
FRONTEND_URLComma-separated string. frontend.allowedOrigins is the full array and drives CORS. frontend.url is the first entry.See env.config.ts
SUPERADMIN_EMAILSComma-separated string. Optional in the schema.See env.config.ts
auth.jwtExpiresIn and other token lifetimesMilliseconds as a string. Parse where used.'900000' (15 minutes) for jwtExpiresIn
redis.urlURLredis://localhost:6379
openai.modelModel name. Rover sends this value as it isgpt-5.2
otp.expiryMinutesMinutes15
DATABASE_POOL_SIZECoerced 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.

ClientName it sendsKeyRetries
Main chatopenai.modelOPENAI_API_KEY8
Small talkopenai.microModelOPENAI_API_KEY0
Slide reader, used by check_slideopenai.modelOPENAI_API_KEYNot set on this constructor
Illustrationsopenai.imageModelOPENAI_API_KEYNot 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_KEY
  • AI_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.

FileUsed for
.env.exampleCommitted template. Task env copies it to .env.local when that file does not exist.
.env.localLocal development. Loaded by the apps and the migration CLI. Not committed.
.env.stagingThe staging deployment
.env.productionProduction
.env.local
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_EMAILS is missing from .env.example. Add it to .env.local to sign in. See Getting started.

Where to go next

On this page