Skip to content

Configuration ​

This guide covers configuration files, environment variables and paths:

  • How it works
  • Config file format
  • Environment variables
  • Filesystem paths
  • Accessing config
  • Path aliases

Ream loads configuration from a config/ directory at your project root. Each file in that directory exports a plain default object and is auto-loaded by Ignitor before any provider is registered.

How it works ​

During the register phase, Ignitor scans every .ts / .js file inside config/, imports its default export, and stores it in the application config store under the file's base name (without extension).

config/database.ts  →  app.config.get('database')
config/auth.ts      →  app.config.get('auth')
config/logger.ts    →  app.config.get('logger')

This happens before providers run, so any provider that calls app.config.get() in its boot() method will always find the values it needs.

Config file format ​

Each config file is a plain TypeScript module that exports a default object. There is no required wrapper — just export what you need.

config/database.ts ​

Read environment variables through #start/env and build filesystem paths with the app path helpers — never process.env or dirname(fileURLToPath(import.meta.url)) directly (see below).

typescript
import app from '@c9up/ream/services/app'
import env from '#start/env.js'

export default {
  client: 'sqlite' as const,
  connection: {
    filename: env.get('DB_PATH', app.makePath('data', 'app.db')),
  },
  migrations: {
    path: app.migrationsPath(),
  },
}

config/auth.ts ​

typescript
import env from '#start/env.js'

export default {
  defaultStrategy: 'jwt',
  jwt: {
    secret: env.get('JWT_SECRET').release(),
    expiresInSeconds: 86400,
  },
}

config/app.ts — the HTTP server ​

The native server guards every connection before a request reaches your code. Its bounds live in the http block of config/app.ts:

typescript
export const http = {
  headersTimeout: 60_000,    // ms to receive a request's headers
  requestTimeout: 300_000,   // ms to receive its body once the headers are in → 408
  keepAliveTimeout: 5_000,   // ms an idle keep-alive connection stays open
  maxConnections: 10_000,    // concurrent connections; extra clients wait in the backlog
  webSocket: {
    maxMessageSize: '1mb',     // largest incoming message → closed 1009
    maxFrameSize: '1mb',       // largest incoming frame → closed 1009
    idleTimeout: 60_000,       // ms of silence: a ping at half, a close (1001) at the end; 0 never
    maxBufferedBytes: '4mb',   // backlog for a client that reads slowly → closed 1013
    allowedOrigins: [],        // browser origins besides the request's own; ['*'] for any
  },
}

The values above are the defaults. 0 turns a bound off (maxConnections: 0 means unbounded). A client that connects and never finishes its headers is closed after headersTimeout; a body that trickles in slower than requestTimeout is answered 408 E_HTTP_REQUEST_TIMEOUT. A WebSocket connection counts toward maxConnections for as long as it is open; the webSocket values above are its defaults (see WebSockets).

Request bodies are also limited at the socket, with the limits of config/bodyparser.ts (see File uploads): nothing past its content type's limit is held in memory. The request still goes through routing without its body, and reading that body answers 413 E_REQUEST_ENTITY_TOO_LARGE through your exception handler.

Environment variables ​

Define and validate your environment in start/env.ts with Env.create, then read variables anywhere through the typed env.get(). The schema loads the .env* files at import time and refuses to boot if a required variable is missing or malformed, so a typo surfaces immediately instead of as a runtime undefined.

typescript
// start/env.ts
import { Env } from '@c9up/ream'

export default await Env.create(new URL('../', import.meta.url), {
  NODE_ENV: Env.schema.enum(['development', 'production', 'test'] as const),
  PORT: Env.schema.number(),
  HOST: Env.schema.string({ format: 'host' }),
  JWT_SECRET: Env.schema.secret(),
  // Optional with `.optional()` — `env.get` then returns `T | undefined`.
  DB_PATH: Env.schema.string.optional(),
  REDIS_URL: Env.schema.string({ format: 'url' }).optional(),
})

Schema types: string({ format?: 'host' | 'url' | 'email' | 'uuid' }), number(), boolean(), enum([...] as const) and secret(), each with an .optional() variant. Validation failures throw E_INVALID_ENV_VARIABLES with an aggregated list.

secret() is for keys, passwords and tokens: env.get() hands back a Secret<string> that prints as [redacted] in logs, JSON.stringify and console.log, and .release() is the one way to read the value.

Read variables in config files via #start/env — importing it is what loads .env before the config is evaluated, in every flow (server, console, tests):

typescript
import env from '#start/env.js'

const port = env.get('PORT')                      // typed `number`
const secret = env.get('JWT_SECRET')              // typed `Secret<string>`, read with .release()
const dbPath = env.get('DB_PATH', '/tmp/app.db')  // fallback

WARNING

Do not read process.env directly in config files, services, or controllers — funnel every variable through start/env.ts so the app has a single, validated source of truth. process.env belongs only to the bootstrap entry points (bin/*.ts, start/env.ts).

A .env file at the project root holds local values. The files are read most specific first, and the first value found for a variable wins — a variable already set in the shell or by the platform beats every file:

  1. .env.<NODE_ENV>.local
  2. .env.local (skipped when NODE_ENV is test, so a developer's overrides never reach the tests)
  3. .env.<NODE_ENV>
  4. .env

NODE_ENV is normalised first (prod reads .env.production, dev reads .env.development, testing reads .env.test). A .env.local left on a production server therefore overrides .env: keep it out of deployments. ENV_PATH names another directory to read the files from (ENV_PATH=/etc/secrets node bin/server.js); when it is set and that directory holds none of the files, the app refuses to boot rather than starting on whatever defaults are around.

env
NODE_ENV=development
PORT=3000
HOST=localhost
# At least 32 random characters (e.g. `openssl rand -base64 48`). Left empty, the app refuses to boot.
JWT_SECRET=

References and identifiers ​

A value can reference another variable with $NAME or ${NAME}; the referenced value is itself interpolated first, so the order of the lines does not matter, and a loop (A=$B, B=$A) stops the boot with E_ENV_CIRCULAR_REFERENCE. \$ keeps a literal dollar sign.

A value that starts with a registered identifier goes through it. file: is built in: it reads the file relative to the project root (an absolute path works too), which is how Docker and Kubernetes secrets reach the app. A missing file stops the boot with E_ENV_FILE_NOT_FOUND, naming the variable and the path.

env
DB_HOST=db.internal
DATABASE_URL=postgres://app@${DB_HOST}/app
DB_PASSWORD=file:/run/secrets/db_password
# The escape: the literal string `file:not-a-path`
MOTTO=file\:not-a-path

Register your own with Env.defineIdentifier(name, (value, key, appRoot) => …), before Env.create runs; the resolver may be async. A name already taken (file included) throws E_IDENTIFIER_ALREADY_DEFINED; Env.defineIdentifierIfMissing registers only when the name is free.

DANGER

Never give a secret a fallback in a config file (env.get('JWT_SECRET') ?? '…', process.env.JWT_SECRET ?? '…'). Config files are committed: the fallback is a value anyone can read, and a deployment that forgets the variable signs every token with it — an authentication bypass. Declare the variable required and let the boot fail.

Filesystem paths ​

Use the app path helpers instead of recomputing dirname(fileURLToPath(import.meta.url)) in every file. They resolve against the project root the Ignitor was constructed with.

typescript
import app from '@c9up/ream/services/app'

app.makePath('data', 'app.db')   // <root>/data/app.db
app.configPath('database.ts')    // <root>/config/database.ts
app.migrationsPath()             // <root>/database/migrations
app.tmpPath('uploads')           // <root>/tmp/uploads
app.publicPath('style.css')      // <root>/public/style.css

There is one helper per conventional directory:

typescript
app.httpControllersPath()   // app/controllers      app.modelsPath()        // app/models
app.servicesPath()          // app/services         app.middlewarePath()    // app/middleware
app.policiesPath()          // app/policies         app.validatorsPath()    // app/validators
app.exceptionsPath()        // app/exceptions       app.eventsPath()        // app/events
app.listenersPath()         // app/listeners        app.transformersPath()  // app/transformers
app.mailersPath()           // app/mailers          app.mailsPath()         // app/mails
app.startPath()             // start                app.commandsPath()      // commands
app.providersPath()         // providers            app.contractsPath()     // contracts
app.viewsPath()             // resources/views      app.languageFilesPath() // resources/lang
app.seedersPath()           // database/seeders     app.factoriesPath()     // database/factories
app.generatedClientPath()   // .ream/client         app.generatedServerPath() // .ream/server

Plus app.makeURL(...), which gives a URL where makePath gives a path — what an importer wants — and app.relativePath(absolute), its inverse.

Moving a directory ​

The layout is not hardcoded. Name the directories that moved in reamrc.ts and every helper follows:

typescript
export default defineConfig({
  directories: {
    httpControllers: 'app/http/controllers',
    models: 'src/entities',
  },
})

Only what you name changes; the rest keep their defaults. The overrides reach the application as soon as the rc file loads, so a provider calling a path helper from register() already sees them.

Generated files live in .ream/

generatedClientPath() and generatedServerPath() write under .ream/.

Accessing config ​

Anywhere you have access to the application instance, call app.config.get<T>() with the config key and an optional generic type argument for type safety.

In a provider ​

typescript
import { Provider } from '@c9up/ream'
import type { AtlasDatabaseConfig } from '@c9up/atlas'

export default class AppProvider extends Provider {
  async boot() {
    const db = this.app.config.get<AtlasDatabaseConfig>('database')
    // db.client, db.connection.filename, etc.
  }
}

In a service ​

typescript
import { app } from '@c9up/ream'

const logLevel = app.config.get<{ level: string }>('logger')?.level ?? 'info'

get<T>() returns T | undefined, so always guard against the undefined case when the config key may not be present.

Path aliases ​

Ream projects use Node.js subpath imports to keep import statements short. Aliases are declared in package.json under the "imports" field, then mirrored in tsconfig.json so TypeScript resolves them too. A project created with ream new declares all of the ones below.

package.json ​

json
{
  "imports": {
    "#app/*": "./app/*",
    "#modules/*": "./app/modules/*",
    "#config/*": "./config/*",
    "#middleware/*": "./app/middleware/*",
    "#exceptions/*": "./app/exceptions/*",
    "#providers/*": "./providers/*",
    "#start/*": "./start/*"
  }
}

tsconfig.json ​

json
{
  "compilerOptions": {
    "paths": {
      "#app/*": ["./app/*"],
      "#modules/*": ["./app/modules/*"],
      "#config/*": ["./config/*"],
      "#middleware/*": ["./app/middleware/*"],
      "#exceptions/*": ["./app/exceptions/*"],
      "#providers/*": ["./providers/*"],
      "#start/*": ["./start/*"]
    }
  }
}

These aliases work in all files that Node.js or the TypeScript compiler resolves — route files, providers, tests, reamrc.ts, and so on.

typescript
// Without alias
import { UserService } from '../../../app/modules/user/services/UserService.js'

// With alias
import { UserService } from '#modules/user/services/UserService.js'

Next steps ​

  • Providers — consume config in the boot lifecycle
  • Atlas (ORM) — database configuration and migrations