Skip to content

Configuration ​

Introduction ​

Plinth keeps every setting in one place: the Config repository. You read values from it with dot-paths such as app.name or database.connections.mysql.host. The values themselves come from plain TypeScript files, one per area (app, database, session, and so on), and those files read their secrets and per-environment differences from environment variables.

This page explains how the repository works, how the generated application fills it, how .env files are read, and how to read settings in a type-safe way.

The config repository ​

Config is exported by @plinthjs/core. You can create one directly from an object:

ts
import { Config } from '@plinthjs/core'

const config = new Config({
  app: { name: 'Blog', debug: false, port: 3000, tags: ['a'] },
  mail: { from: { name: 'Blog Team' } },
})

config.get('app.name') // => 'Blog'
config.get('mail.from.name') // => 'Blog Team'
config.get('app.missing', 'fallback') // => 'fallback'
config.has('app.debug') // => true (a false value still counts as present)
config.has('app.missing') // => false

In an application you rarely build a Config yourself. The Application creates one from the config option you pass it and exposes it as app.config:

ts
import { Application } from '@plinthjs/core'

const app = new Application({ config: { app: { name: 'Blog' } } })
app.config.get('app.name') // => 'Blog'

The config is also bound in the container, so you can resolve it with app.make(Config).

Setting and changing values ​

set writes a value at a dot-path and creates any missing intermediate objects. push and prepend add to an array value, treating a missing key as an empty array. merge shallowly merges whole top-level sections, and all returns the complete tree:

ts
config.set('app.timezone', 'UTC')

config.push('app.tags', 'b').prepend('app.tags', 'z')
config.get('app.tags') // => ['z', 'a', 'b']

config.merge({ cache: { default: 'file' } })
Object.keys(config.all()) // => ['app', 'mail', 'cache']

config.getMany(['app.name', 'app.port', 'nope'])
// => { 'app.name': 'Blog', 'app.port': 3000, nope: undefined }

WARNING

merge replaces whole top-level keys. Merging { app: { name: 'X' } } replaces the entire app section, it does not combine it with the existing one. To add defaults without overriding what is already there, use mergeConfigFrom in a service provider.

Typed getters ​

get returns whatever is stored. When a value must be a particular type, use a typed getter. It checks the type at runtime and throws a descriptive TypeError if the value is wrong, so a bad setting fails loudly at the point you read it:

ts
config.string('app.name') // => 'Blog'
config.integer('app.port') // => 3000
config.float('app.port') // => 3000 (any finite number passes)
config.boolean('app.debug') // => false
config.array('app.tags') // => ['z', 'a', 'b']

Each getter accepts a default as its second argument, used when the key is missing:

ts
config.integer('session.lifetime', 120) // => 120 when unset

When the value has the wrong type, the error says which key and what it found:

ts
config.integer('app.name')
// TypeError: Configuration value for key [app.name] must be an integer, string given.

config.string('missing')
// TypeError: Configuration value for key [missing] must be a string, undefined given.

The generated app uses these getters for values it cannot do without, such as config.integer('session.lifetime', 120) and config.boolean('app.debug', false).

Configuration files ​

A generated app keeps its configuration in src/config/. Each file default-exports a plain object:

ts
// src/config/app.ts
import { env } from '@plinthjs/core'

export default {
  name: env('APP_NAME', 'blog'),
  env: env('APP_ENV', 'production'),
  debug: env('APP_DEBUG', false),
  url: env('APP_URL', 'http://localhost'),
  timezone: 'UTC',
  locale: env('APP_LOCALE', 'en'),
  fallbackLocale: env('APP_FALLBACK_LOCALE', 'en'),
  key: env('APP_KEY', ''),
  cipher: 'aes-256-gcm',
}

The scaffold ships these files: app, auth, cache, database, filesystems, hashing, logging, mail, queue, services, and session. They are loaded in src/bootstrap/app.ts, which imports each one and passes them to the Application under a key named after the file:

ts
const app = new Application({
  basePath: process.cwd(),
  config: {
    app: appConfig,
    database: databaseConfig,
    session: sessionConfig,
    // ...
  },
})

That is why app.name and database.default work as dot-paths. To add a new configuration area, create a file in src/config/, import it in bootstrap/app.ts, and add it to the config object.

INFO

The config files describe settings for the packages your app uses. A file such as src/config/mail.ts takes effect only when your code reads it, typically from a service provider that builds a mailer. The generated app reads app, database, session, and logging; the others are ready for when you install the matching package.

Reading config in your code ​

Inside the generated app, the app() helper in src/support/container.ts returns the booted application, so any code that runs after boot can read settings:

ts
import { app } from '../Support/container.js'

const name = app().config.string('app.name')

In a service provider the application is available as this.app, so this.app.config.get('database.default') works inside register and boot.

Environment variables ​

Values that change between machines or that must stay secret belong in environment variables. The env helper reads one and applies a few conversions so that .env strings turn into useful TypeScript values:

ts
import { env } from '@plinthjs/core'

env('APP_DEBUG', false) // true when APP_DEBUG=true, false when APP_DEBUG=false
env('APP_NAME', 'Blog') // the string, or 'Blog' when unset
env('MISSING') // => undefined
env('MISSING', 5) // => 5
env('MISSING', () => computeDefault()) // a function default is called when unset

The conversions apply to the raw string, ignoring case:

Raw valueResult
true / falsetrue / false
null or (null)null
empty or (empty)'' (empty string)
an integer or decimala number
anything elsethe string unchanged

WARNING

Unquoted numeric strings become numbers. DB_PASSWORD=12345 is read as the number 12345. An integer with a leading zero such as 007 or 00123 stays a string, so zip codes and ids keep their digits. A value you wrap in single or double quotes in .env is never converted: ZIP="90210" reads back as the string "90210". This applies to values loaded with loadDotenv (the generated src/bootstrap/env.ts uses it); variables set in the real environment are plain strings and follow the table above. If a setting must stay a string regardless, wrap it when you read it, for example String(env('DB_PASSWORD', '')).

env accepts an optional third argument, a plain object to read from instead of process.env. That is handy in tests:

ts
env('PORT', '3000', { PORT: '8080' }) // => 8080

The .env file ​

Locally, you keep environment variables in a .env file at the project root. The scaffold creates one from .env.example, which documents every key the app understands:

bash
APP_NAME=blog
APP_ENV=local
APP_DEBUG=true
APP_KEY=base64:...
DB_CONNECTION=sqlite
# DB_DATABASE is a file path for sqlite and a database name for mysql/mariadb
DB_DATABASE=storage/database.sqlite
# DB_MIGRATIONS_TABLE=migrations   # only if the database is shared with another tool's migrations table
SESSION_DRIVER=file

Commit .env.example, never .env: the generated .gitignore already excludes it.

The file is loaded by src/bootstrap/env.ts, which bootstrap/app.ts imports first so the values exist before any config file is evaluated. It uses parseDotenv from @plinthjs/core:

ts
import { parseDotenv } from '@plinthjs/core'

parseDotenv(`
# a comment
APP_NAME="My App"
export APP_ENV=local
GREETING='hello $world'
MULTI="line1\\nline2"
PORT=3000 # inline comment
`)
// => {
//   APP_NAME: 'My App',
//   APP_ENV: 'local',
//   GREETING: 'hello $world',
//   MULTI: 'line1\nline2',
//   PORT: '3000',
// }

The parser understands KEY=value, an optional export prefix, # comments, blank lines, single and double quotes, and the \n, \t and \" escapes inside double quotes. An unquoted value stops at a space followed by #. Single-quoted values are taken literally. The parser does not expand $VARIABLE references.

parseDotenv only returns an object. The generated bootstrap/env.ts copies each pair into process.env, but only when the variable is not already set:

ts
for (const [key, value] of Object.entries(parsed)) {
  if (process.env[key] === undefined) process.env[key] = value
}

This means real environment variables win over the file. A variable set by your shell, your container, or your hosting platform overrides the same key in .env. A missing .env file is fine: the app falls back to the real environment and the defaults in the config files.

Environment detection ​

The application knows which environment it is running in. It reads app.env from the config (which comes from APP_ENV), falls back to the APP_ENV variable, and finally defaults to production:

ts
const app = new Application({ config: { app: { env: 'local' } } })

app.environment() // => 'local'
app.environment('local', 'testing') // => true (matches any name given)
app.isLocal() // => true
app.isProduction() // => false
app.runningUnitTests() // => false (true only when the environment is 'testing')

The scaffolded .env sets APP_ENV=local, while the default in config/app.ts is production. That default is deliberate: a deployment that forgets to set APP_ENV fails safe, with debugging output off.

The environment drives real behaviour in the generated app: in production it sends HSTS headers, skips console logging, caches compiled views, and refuses to start without an APP_KEY. See Deployment.

APP_DEBUG is separate from the environment. It decides whether the exception handler shows real error messages (true) or a generic 500 page (false). See Error Handling.

Paths ​

The application also provides helpers for the standard directories. They join onto the basePath option, or onto process.cwd() when none was given:

ts
const app = new Application({ basePath: '/srv/blog' })

app.path('x') // => '/srv/blog/x'
app.storagePath('logs') // => '/srv/blog/storage/logs'
app.publicPath() // => '/srv/blog/public'
app.resourcePath('views') // => '/srv/blog/resources/views'

WARNING

The helpers use the directory names config, storage, database, public, bootstrap, and resources directly under the base path. The generated app keeps config, database, and bootstrap under src/, so app.configPath() does not point at src/config. Build those paths yourself with app.path('src', 'config').

Caching configuration ​

Building the config tree is cheap, but you can snapshot it. cache() returns a serialisable, deep-cloned copy of the tree, and Config.loadCached() (or the cached constructor option) rebuilds a repository from it without evaluating any config module:

ts
const snapshot = config.cache()
// snapshot is { items: { ... } }, safe to JSON.stringify and store

const restored = Config.loadCached(snapshot)
restored.get('cache.default') // => 'file'

const same = new Config({}, { cached: snapshot })

The snapshot is a copy, so later changes to the original repository do not affect it. Plinth does not write the snapshot to disk for you; if you want a build step that stores it, serialise config.cache() yourself and read it back at startup.

Testing with config ​

Because Config is just an object, tests can build an Application with exactly the settings they need and avoid touching .env:

ts
const app = new Application({
  config: { app: { env: 'testing', debug: true }, database: { default: 'sqlite' } },
})
app.runningUnitTests() // => true

Use the third argument of env to feed a fake environment to code that reads variables directly.

Released under the MIT License.