Skip to content

Configuration ​

@forinda/kickjs ships schema-validated environment configuration with caching, an injectable typed service, and tight integration with kick typegen — every API in this guide is type-safe with no manual schema passing. No extra package install is required.

Example

settings-api: settings sections, .scoped() adapters, _FILE secrets and the DevTools Config tab. More in Examples.

Moved from @forinda/kickjs-config

Earlier releases shipped these APIs in a separate @forinda/kickjs-config package. They now live inside @forinda/kickjs itself. The standalone package still exists as a thin re-export shim for one release and will be removed in v3 — migrate your imports to @forinda/kickjs.

.env file loading uses dotenv, which is now an optional peer dependency. New projects scaffolded with kick new get it pre-installed; existing projects should add it explicitly if they rely on .env files (pnpm add dotenv). Apps that load env via the shell, Docker, or a secret manager can skip it entirely.

Defining an Environment Schema ​

The recommended pattern: put your schema in src/config/index.ts as a default export (older scaffolds put it at src/env.ts — both still work; the typegen scanner searches both). kick new creates this file for you, and kick typegen (auto-run on kick dev) reads it once and populates the global KickEnv interface — that's what makes ConfigService.get, loadEnv, getEnv, process.env, and @Value all type-safe across the project.

Wrap your schema with fromZod / fromValibot / fromYup from @forinda/kickjs-schema and load it with loadEnvFromSchema(envSchema). The wrapped schema is what kick typegen reads to populate KickEnv, and the same wrapped schema flows through the validate middleware and the swagger spec generator — all three pipelines share one definition. Pick whichever library you prefer:

ts
// src/config/index.ts — Zod (recommended default)
import { loadEnvFromSchema } from '@forinda/kickjs/config'
import { fromZod } from '@forinda/kickjs-schema/zod'
import { z } from 'zod'

const envSchema = fromZod(
  z.object({
    PORT: z.coerce.number().default(3000),
    NODE_ENV: z.enum(['development', 'production', 'test']).default('development'),
    LOG_LEVEL: z.string().default('info'),
    DATABASE_URL: z.string().url(),
    JWT_SECRET: z.string().min(32),
    REDIS_URL: z.string().url().optional(),
  }),
)

loadEnvFromSchema(envSchema) // side effect: registers the schema
export default envSchema
ts
// src/config/index.ts — Valibot
import { loadEnvFromSchema } from '@forinda/kickjs/config'
import { fromValibot } from '@forinda/kickjs-schema/valibot'
import * as v from 'valibot'

const envSchema = fromValibot(
  v.object({
    PORT: v.optional(v.pipe(v.string(), v.transform(Number)), '3000'),
    NODE_ENV: v.optional(v.picklist(['development', 'production', 'test']), 'development'),
    LOG_LEVEL: v.optional(v.string(), 'info'),
    DATABASE_URL: v.pipe(v.string(), v.url()),
    JWT_SECRET: v.pipe(v.string(), v.minLength(32)),
  }),
)

loadEnvFromSchema(envSchema) // side effect: registers the schema
export default envSchema
ts
// src/config/index.ts — Yup
import { loadEnvFromSchema } from '@forinda/kickjs/config'
import { fromYup } from '@forinda/kickjs-schema/yup'
import * as yup from 'yup'

const envSchema = fromYup(
  yup.object({
    PORT: yup.number().default(3000),
    NODE_ENV: yup.string().oneOf(['development', 'production', 'test']).default('development'),
    LOG_LEVEL: yup.string().default('info'),
    // Yup's `.url()` only matches http/https — use `.string().required()` for
    // database URLs like `postgres://…` or write a custom `.matches(/^…/)`.
    DATABASE_URL: yup.string().required(),
    JWT_SECRET: yup.string().min(32).required(),
  }),
)

loadEnvFromSchema(envSchema) // side effect: registers the schema
export default envSchema

The file registers the schema and exports it for kick typegen — it exports no parsed env object. Read values anywhere with getEnv('DATABASE_URL') from @forinda/kickjs (typed from the schema), an injected ConfigService, or @Value; src/index.ts and tests import ./config only for its side effect.

Scaffold straight from the CLI

kick new --schema zod (default), --schema valibot, or --schema yup writes the right src/config/index.ts for you and sets typegen.schemaValidator: 'kickjs-schema' in kick.config.ts so type generation flows through InferSchemaOutput. See CLI commands for the full flag list.

For the KickSchema interface, adapter behaviour, and a deeper look at InferSchemaOutput, jump to the schema-agnostic validation guide. Once src/config/index.ts exists, run kick typegen once (or just start kick dev) and the schema flows through to every consumer automatically — see Type Generation for the full pipeline.

Legacy: defineEnv + loadEnv (Zod-only) ​

Older pattern — still supported, not removed

Projects scaffolded before the @forinda/kickjs-schema integration use defineEnv() + loadEnv() directly against Zod. Both APIs still ship and kick typegen still detects the schema (set typegen.schemaValidator: 'zod' to keep the legacy z.infer<typeof envSchema> codegen). New projects should prefer the schema-agnostic pattern above; existing projects can migrate at their own pace.

ts
// Legacy — Zod-only, still works
import { defineEnv } from '@forinda/kickjs'
import { z } from 'zod'

export default defineEnv((base) =>
  base.extend({
    DATABASE_URL: z.string().url(),
    JWT_SECRET: z.string().min(32),
    REDIS_URL: z.string().url().optional(),
  }),
)

Wiring the schema at startup ​

Required: side-effect import

The schema is a declaration only. You must also call loadEnvFromSchema(envSchema) (the canonical pattern above does this for you) and make sure that file is imported as a side effect from src/index.ts before bootstrap() runs. If you skip this:

  • ConfigService.get('YOUR_KEY') returns undefined for every user-defined key.
  • loadEnv() (no-arg) falls back to baseEnvSchema and only knows PORT, NODE_ENV, LOG_LEVEL.
  • @Value('YOUR_KEY') appears to keep working — but only because it has a raw process.env fallback baked in. The validated typed value is not available, the schema's defaults never apply, and Zod coercions / Valibot transforms silently drop. This is the divergence that causes "ConfigService doesn't see my env" bug reports.

kick new scaffolds both halves of the wiring for you. If you're upgrading an older project by hand, follow the canonical patterns above.

The canonical src/config/index.ts calls loadEnvFromSchema(envSchema) itself so the file does double duty as both a schema declaration and a runtime registration. Legacy projects can keep using loadEnv(envSchema) against a defineEnv schema — the wiring requirement is identical:

ts
// Legacy — still supported. New projects: use loadEnvFromSchema + fromZod (see above).
import { defineEnv, loadEnv } from '@forinda/kickjs/config'
import { z } from 'zod'

const envSchema = defineEnv((base) =>
  base.extend({
    DATABASE_URL: z.string().url(),
    JWT_SECRET: z.string().min(32),
  }),
)

// Side-effect: register the extended schema with kickjs's env cache
// **at module-load time**. ConfigService and @Value() both consume
// this cache.
loadEnv(envSchema)

export default envSchema

And src/index.ts pulls it in before bootstrap():

ts
// src/index.ts
import 'reflect-metadata'
// Side-effect import — must come BEFORE any kickjs imports that pull
// in @Service / @Controller / @Value, so the env cache is populated
// when DI starts wiring instances.
import './config'

import { bootstrap } from '@forinda/kickjs'
import { modules } from './modules'

export const app = await bootstrap({ modules })

To pick up .env file changes during dev without restarting the server, add envWatchPlugin() to vite.config.ts (the kick new scaffold does this for you):

ts
// vite.config.ts
import { defineConfig } from 'vite'
import swc from 'unplugin-swc'
import { kickjsVitePlugin, envWatchPlugin } from '@forinda/kickjs-vite'

export default defineConfig({
  plugins: [swc.vite(), kickjsVitePlugin({ entry: 'src/index.ts' }), envWatchPlugin()],
})

Why this matters ​

ConfigService reads through loadEnv() lazily on every get call — so once loadEnv(extendedSchema) has been called anywhere in the app, every ConfigService instance (whether resolved before or after) sees the extended values. The catch is "anywhere": if src/env.ts is never imported, loadEnv(extendedSchema) never runs and the cached schema stays empty (or downgrades to the base shape).

@Value() masks this bug because it has a defensive process.env[key] fallback. ConfigService deliberately does not — it returns whatever the validated env cache holds, so calls to config.get('CUSTOM_KEY') come back undefined until the schema has been registered. Treat ConfigService.get returning undefined for a known-good .env value as a strong signal that src/env.ts is not being imported at startup.

The base schema provides these defaults:

VariableTypeDefault
PORTnumber3000
NODE_ENV'development' | 'production' | 'test''development'
LOG_LEVELstring'info'

Loading and Accessing Environment Variables ​

loadEnvFromSchema ​

Parse and validate process.env against any wrapped KickSchema — Zod, Valibot, Yup, or any future adapter. Returns the typed env data; caches the result so subsequent reads through loadEnv() / ConfigService reuse the same parsed object.

ts
import { loadEnvFromSchema } from '@forinda/kickjs/config'
import { fromZod } from '@forinda/kickjs-schema/zod'
import { z } from 'zod'

const envSchema = fromZod(
  z.object({
    DATABASE_URL: z.string().url(),
    PORT: z.coerce.number().default(3000),
  }),
)

const env = loadEnvFromSchema(envSchema)
env.DATABASE_URL // string (inferred from the wrapped schema)
env.PORT // number

The return type is InferSchemaOutput<TSchema> — Zod's _output (via the Standard Schema brand on v4), Valibot's ~standard.types.output, or Yup's __outputType. Pass a runtime-only validator (a plain function) and the return type degrades to Record<string, unknown> automatically. Validation failure throws a single Error whose message lists every field that failed; the safeParse shape underneath is the same one swagger and the validate middleware use.

loadEnv (legacy — Zod only) ​

Older API — still supported, not removed

loadEnv() accepts only Zod schemas and predates loadEnvFromSchema. New projects should prefer loadEnvFromSchema so the env shares the same KickSchema abstraction as body validation and swagger.

ts
import { loadEnv } from '@forinda/kickjs'

// No-arg form — returns KickEnv when typegen has populated it,
// otherwise returns the base Env shape.
const env = loadEnv()
env.DATABASE_URL // string (typed from src/env.ts)
env.PORT // number

// Explicit-schema form — useful for tests or one-off scripts that
// need a different schema than the project default.
const testEnv = loadEnv(testSchema)

The cache is sticky across both APIs: once you've called loadEnvFromSchema(extendedSchema) or loadEnv(extendedSchema) once, subsequent loadEnv() calls reuse the extended schema instead of falling back to the base. This matters because ConfigService (and the bare @Value resolver) call loadEnv() no-arg internally — without stickiness, instantiating them after a custom schema load would silently downgrade the env.

getEnv ​

Retrieve a single variable. With typegen active, the key is constrained to known KickEnv keys and the return type is inferred:

ts
import { getEnv } from '@forinda/kickjs'

const port = getEnv('PORT') // number (Zod-coerced)
const url = getEnv('DATABASE_URL') // string
// const bad = getEnv('NOPE')      // ❌ tsc error

You can still pass an explicit schema as the second argument when you need a one-off shape outside the project default.

reloadEnv vs resetEnvCache ​

reloadEnv() and resetEnvCache() look similar but answer different questions, and using the wrong one in dev produces a subtle "user keys disappear" bug. Pick the right tool:

FunctionClears parsed values?Clears registered schema?Use when
reloadEnv()yesnoa .env file changed; you want fresh values against the same schema. Called automatically by envWatchPlugin() and the kickjs HMR rebuild path.
resetEnvCache()yesyesa test wants a totally fresh slate, e.g. swapping envSchema between cases.

reloadEnv() deliberately keeps the registered schema so the next read re-parses process.env against your extended shape instead of falling back to the base schema. If it dropped the schema instead, every ConfigService.get('CUSTOM_KEY') after a .env save would silently start returning undefined — which is exactly the bug HMR users would hit on every reload before this fix.

If you need to swap schemas between cases (typically only in tests), call resetEnvCache() then loadEnv(newSchema):

ts
import { resetEnvCache, loadEnv } from '@forinda/kickjs'

resetEnvCache()
process.env.PORT = '4000'
const env = loadEnv(envSchema) // re-parsed with new PORT against fresh schema

For the normal "edit .env, want the new value" flow, do nothing — envWatchPlugin() calls reloadEnv() for you and ConfigService.get() immediately returns the new value.

Which .env files load ​

The mode is NODE_ENV (development when unset; always test under Vitest). Files are read from the working directory, highest precedence first:

.env.[mode].local  >  .env.[mode]  >  .env.local  >  .env

At startup, a variable already set in the shell, Docker or the platform beats every file. A kick dev reload after a file edit (reloadEnv()) reads the files with override on, so there a file's value replaces one exported in the shell — restart the dev server to get the shell value back. Under test, a .env.test or .env.test.local replaces the generic files instead of layering over them (see Testing: environment).

Files somewhere else: KICKJS_ENV_FILE ​

KICKJS_ENV_FILE replaces that lookup with your own list — comma-separated, highest precedence first. Relative paths resolve against the working directory; absolute paths are used as they are:

bash
KICKJS_ENV_FILE=/etc/my-app/.env node dist/index.js                  # one file outside the project
KICKJS_ENV_FILE=config/.env.production,config/.env node dist/index.js # override plus base
KICKJS_ENV_FILE=off node dist/index.js                               # no files: env from the platform

kick dev reloads when any of these files changes — the listed ones, or the four above for the current mode.

Secrets from files (<KEY>_FILE) ​

Docker secrets, Kubernetes secret volumes and most secret managers mount secrets as files rather than environment variables. For any key your env schema declares, set <KEY>_FILE to the file's path and the value is read from it:

bash
DB_PASSWORD_FILE=/run/secrets/db_password
ts
const envSchema = z.object({ DB_PASSWORD: z.string().min(1) })
loadEnv(envSchema).DB_PASSWORD // the file's contents

Each key reads its own file, so several secrets sit side by side with ordinary variables. With Docker Compose:

yaml
services:
  api:
    image: my-app
    environment:
      AWS_REGION: eu-west-1 # ordinary variable
      DB_PASSWORD_FILE: /run/secrets/db_password
      JWT_SECRET_FILE: /run/secrets/jwt_secret
      STRIPE_KEY_FILE: /run/secrets/stripe_key
    secrets: [db_password, jwt_secret, stripe_key]

secrets:
  db_password: { file: ./secrets/db_password.txt }
  jwt_secret: { file: ./secrets/jwt_secret.txt }
  stripe_key: { file: ./secrets/stripe_key.txt }

On Kubernetes, mount the Secret as a volume and point each _FILE variable into it:

yaml
containers:
  - name: api
    env:
      - { name: DB_PASSWORD_FILE, value: /etc/secrets/db_password }
      - { name: JWT_SECRET_FILE, value: /etc/secrets/jwt_secret }
      - { name: STRIPE_KEY_FILE, value: /etc/secrets/stripe_key }
    volumeMounts:
      - { name: secrets, mountPath: /etc/secrets, readOnly: true }
volumes:
  - name: secrets
    secret: { secretName: api-secrets }

The schema is unchanged — it declares DB_PASSWORD, JWT_SECRET and STRIPE_KEY, and validates the file contents exactly as it would an environment variable (a STRIPE_KEY failing startsWith('sk_') still fails startup):

ts
const envSchema = z.object({
  AWS_REGION: z.string(),
  DB_PASSWORD: z.string().min(1),
  JWT_SECRET: z.string().min(32),
  STRIPE_KEY: z.string().startsWith('sk_'),
})
  • Only keys in the schema — LOG_FILE meaning "where to write logs" is left alone unless the schema declares LOG.
  • One trailing newline (\n or \r\n, as echo and Windows editors leave) is dropped.
  • Setting both DB_PASSWORD and DB_PASSWORD_FILE fails at startup, so which secret is in use is never ambiguous; so does a file that can't be read. Neither error prints the contents.
  • The value reaches the parsed env — getEnv, ConfigService, @Value — but is not copied into process.env, which child processes inherit. Read it through the schema, not process.env.DB_PASSWORD.

Settings sections (defineSettings) ​

One flat env schema gets crowded, and every service reads from all of it. A settings section groups a concern's configuration under one prefix, with its own schema, and is injected only where it's needed:

ts
// src/modules/db/db.settings.ts
import { defineSettings } from '@forinda/kickjs'
import { z } from 'zod'

export const DbSettings = defineSettings(
  'DB',
  z.object({
    url: z.string().url(),
    pool: z.object({ max: z.coerce.number().int().default(10) }).default({ max: 10 }),
    replicas: z.array(z.string()).default([]),
    ssl: z.stringbool().default(false),
  }),
)

Each key path becomes one env variable under the prefix, in UPPER_SNAKE_CASE:

KeyVariable
urlDB_URL
pool.maxDB_POOL_MAX
replicasDB_REPLICAS — a list, comma-separated: r1.db,r2.db
sslDB_SSL

DbSettings.envNames lists them, and <NAME>_FILE secrets work for every one (DB_URL_FILE=/run/secrets/db_url).

Where sections live ​

Put a section next to the code that uses it — src/modules/db/db.settings.ts — and import its token from there. Not in src/config: that file registers the app-wide env schema as a side effect and is imported once, first, by src/index.ts; a section has no side effect (the environment is read at startup or on get()), so it can be imported from anywhere, in any order. .env files are loaded by @forinda/kickjs itself, so sections see them even in an app without an env schema.

Any schema library ​

Valibot and Yup work as well as Zod — anything @forinda/kickjs-schema reads, as long as it's an object schema (the keys are what become variable names):

ts
import * as v from 'valibot'

export const MailSettings = defineSettings(
  'MAIL',
  v.object({
    host: v.string(),
    port: v.pipe(v.string(), v.transform(Number), v.number()),
  }),
)

Variables are strings, so let the schema convert them: z.coerce.number(), v.pipe(v.string(), v.transform(Number)), or Yup's number() (which casts). For booleans use z.stringbool() — z.coerce.boolean() reads the string 'false' as true.

Using a section ​

Injected, in a service or controller:

ts
import { Inject, Service, type SettingsOf } from '@forinda/kickjs'

@Service()
export class Database {
  constructor(@Inject(DbSettings) private readonly db: SettingsOf<typeof DbSettings>) {}
}

Anywhere else — a plain function, a script, a factory outside DI — call get():

ts
const { url, pool } = DbSettings.get()

get() returns what injected code sees — the value validated at startup, or a replacement bound in the container (below) — so it's cheap and never disagrees with DI. Called before the app starts (a CLI script, a seed file), the first call loads and validates it. DbSettings.load(env?) parses afresh — from process.env, or an env object you pass — when you need the current values instead.

After a .env edit ​

Under kick dev, saving, creating or deleting a .env file in the project root (.env, .env.local, .env.<mode>) re-reads the environment and rebuilds the app: declared sections are read and validated again, so a bad value fails the rebuild, and services are created again in a fresh container. Optional and undeclared sections are read again too, but validated on their next get(), as at startup, so a bad value there fails the code that uses it, not the rebuild. Code that reads a section when it runs sees the new values with no restart:

  • an injected section (@Inject(DbSettings)) is the new value in the rebuilt service
  • DbSettings.get() returns the new value from the next call

What doesn't follow is a value captured once, outside the app, in a module the reload doesn't re-run:

ts
// ✗ read once when the file is imported: stays the old value after a .env edit
const { url } = DbSettings.get()
export const pool = createPool(url)

// ✓ read when the app builds it: rebuilt with the new value
@Service()
export class Database {
  readonly pool: Pool
  constructor(@Inject(DbSettings) db: SettingsOf<typeof DbSettings>) {
    this.pool = createPool(db.url)
  }
}

The same goes for a client built from a section: build it in a service or a factory (container.registerFactory(...)) so the rebuild builds it again. s3FromSettings() from @forinda/kickjs-storage/settings does this itself: it builds the storage on first use and again whenever its section's value changes.

Outside kick dev, the environment is read once when the app starts: a deployed app takes new values on restart. A script that wants fresh values mid-run calls reloadEnv(), then get(), for a section it hasn't bound. If the script started an app, its sections are bound and get() returns the binding: DbSettings.load() parses the current environment instead (injected values stay as they were).

Listing every variable: .env.example ​

kick env example writes .env.example from the env schema and the declared sections — required variables bare, optional ones commented with their default — and --check fails CI when it's stale. In code, app.describeConfig() returns the same list without reading or validating the environment. See kick env example.

Where a value came from ​

"Why is the pool size 10?" app.configOrigins() answers it for every variable the app reads: set in env, read from a _FILE secret (file), the schema's default, supplied by provide() (provided), or unset. It returns names and origins, never values, so it's safe to log or show. DevTools serves it at /_debug/config.

ts
app.configOrigins().sections
// [{ prefix: 'DB', vars: [{ name: 'DB_URL', origin: 'file' }, { name: 'DB_POOL_MAX', origin: 'default' }] }]

From an adapter or a module ​

A declared section is an ordinary DI token, bound before the code that declared it runs, so the usual patterns work.

Configure an adapter from it — defineAdapter's .async() injects tokens into its config factory:

ts
bootstrap({
  modules,
  adapters: [
    DatabaseAdapter.async({
      inject: [DbSettings],
      useFactory: (db: SettingsOf<typeof DbSettings>) => ({ url: db.url, poolSize: db.pool.max }),
    }),
  ],
})

Bind a value under a module's own token — when a library expects DB_URL, not your section:

ts
export const DbModule = defineModule({
  name: 'DbModule',
  build: () => ({
    register(container) {
      container.registerFactory(DB_URL, () => container.resolve(DbSettings).url)
    },
    routes: () => null,
  }),
})

Replace the section — in a module's register(), or in a test — by binding the token again. Injected code and DbSettings.get() both see the replacement:

ts
container.registerInstance(DbSettings, { ...DbSettings.load(), url: 'postgres://localhost/test' })

The container is one per process, so there's no per-module copy: whatever binds last is what every module sees.

Declaring a section ​

A section is validated, and bound for injection, when something the app mounts declares it. Declare it where it's needed:

ts
// App-wide
bootstrap({ modules, settings: [AppSettings] })

// With a module — only when the module is mounted, and bound before its register() runs
export const DbModule = defineModule({
  name: 'DbModule',
  build: () => ({
    settings: () => [DbSettings],
    routes: () => ({ path: '/db', controller: DbController }),
  }),
})

// With an adapter — only when it's enabled (see `when`), and bound before any hook runs
export const SearchAdapter = defineAdapter({
  name: 'SearchAdapter',
  build: () => ({ settings: () => [SearchSettings] /* , hooks */ }),
})

// With a plugin
export const BillingPlugin = definePlugin({
  name: 'BillingPlugin',
  build: () => ({ settings: () => [StripeSettings] /* , modules, adapters */ }),
})

At startup, every declared section is validated, and an invalid or missing value fails startup with the variables to fix:

Settings 'DB' are invalid:
  DB_URL: Invalid URL
  DB_POOL_MAX: Invalid input: expected number, received NaN
  • Only what's mounted is required. A module that isn't loaded doesn't need its variables — including in tests, which give the values for what they mount (.env.test, or schema defaults).
  • Declaring twice is fine — a section shared by a module and an adapter is loaded once. Two different sections with the same prefix would read the same variables and are refused.
  • Undeclared sections aren't validated at startup; get() validates one on first use. They're also missing from .env.example — declare them .optional() (below) to list them.
  • On the web entry, createWebApp({ settings }) and its modules' sections read the env you pass (the Workers bindings).

Read only on some paths: .optional() ​

A section that only one driver reads, picked at run time — SMTP when MAIL_DRIVER=smtp, Resend when it's resend, ClamAV when CLAMAV_HOST is set — can't be declared plainly: startup would require SMTP_HOST in an app that prints its mail. Left undeclared, it works (get() validates it when the driver is built) but kick env example never lists it. Declare it .optional():

ts
export const MailAdapter = defineAdapter({
  name: 'MailAdapter',
  build: () => ({
    settings: () => [SmtpSettings.optional(), ResendSettings.optional()],
    // …picks a driver from MAIL_DRIVER, which calls SmtpSettings.get() or ResendSettings.get()
  }),
})

An optional section is listed by kick env example and app.describeConfig() — every variable commented, the required ones marked required when used — but isn't validated or bound at startup; get() validates it on use. .optional() works in every settings list: bootstrap({ settings }), a module's, an adapter's, a plugin's. Declared plainly anywhere as well, the section is required.

A library's section that your app reads conditionally is declared the same way, from your app — for a bucket only production uses:

ts
import { S3Settings } from '@forinda/kickjs-storage/settings'

bootstrap({ modules, settings: [S3Settings.optional()] })

A description on the section's schema — z.object({ … }).describe('With MAIL_DRIVER=smtp: any SMTP relay.') — is written under its heading in .env.example.

Several instances: .scoped() ​

Two databases, two mail providers — one schema, several prefixes. .scoped(name) puts the name in front of the prefix and returns a separate section (the same one each time for the same name):

ts
export const AnalyticsDb = DbSettings.scoped('ANALYTICS') // reads ANALYTICS_DB_URL, ANALYTICS_DB_POOL_MAX, …

bootstrap({ modules, settings: [DbSettings, AnalyticsDb] })

@Service()
class Reports {
  constructor(@Inject(AnalyticsDb) private readonly db: SettingsOf<typeof AnalyticsDb>) {}
}

Supplying the value: .provide() ​

Sometimes the value doesn't come from the environment — a test container's URL, a port picked at run time. .provide(value) declares the section with that value instead of reading env:

ts
bootstrap({ modules, settings: [DbSettings.provide({ url: pg.url })] })

The value is validated like env (defaults applied, a bad value fails startup naming the variables), and it wins over the same section declared elsewhere — by a module or an adapter — so nothing reads env for it. DbSettings.parse(value) runs the same validation without declaring anything. In tests, startService() hands you the URL to provide.

Accessing Config in Services ​

ConfigService is the recommended way to read env config from a DI-managed class. It's an injectable singleton that consumes the KickEnv global populated by kick typegen, so as long as your src/env.ts is in place you get full type safety with zero extra setup — no schema to pass around, no separate typed-service factory, no manual casts.

ts
import { Service, Autowired, ConfigService } from '@forinda/kickjs'

@Service()
class DatabaseService {
  @Autowired() private readonly config!: ConfigService

  connect() {
    const url = this.config.get('DATABASE_URL') // string — autocompletes from src/env.ts
    const port = this.config.get('PORT') // number — Zod-coerced from baseEnvSchema
    // const bad = this.config.get('NOPE')  // ❌ tsc error: '"NOPE"' is not assignable to 'never'
  }
}

config.getAll() returns Readonly<KickEnv> — every known key is typed and you get autocomplete on the entire config object.

How it knows the schema ​

Once kick typegen has run, ConfigService.get, loadEnv, getEnv, @Value and process.env all know your schema's keys and types — see Type Generation for the details.

Without typegen (legacy projects) ​

If KickEnv is empty (no src/env.ts, or you've disabled env typegen), ConfigService.get falls back to its previous untyped signature so existing call sites keep compiling:

ts
const url = this.config.get<string, string>('DATABASE_URL') // explicit T generic

A second argument is a fallback, returned when the value is unset (undefined or null), for a key the schema leaves optional:

ts
const region = this.config.get('S3_REGION', 'eu-west-1') // string, never undefined

The two-generic form get<K, T> lets you supply a return type when typegen isn't available. With typegen active, the explicit T is ignored and the schema-inferred type wins.

loadEnv and getEnv outside DI ​

For module-scope access (utilities, startup code, scripts), use loadEnv() and getEnv() directly. Both consume KickEnv when available:

ts
import { loadEnv, getEnv } from '@forinda/kickjs'

// loadEnv() with no arg returns KickEnv when typegen has run
const env = loadEnv()
env.DATABASE_URL // string
env.PORT // number

// getEnv() reads one key, typed from the schema
const port = getEnv('PORT') // number
const secret = getEnv('JWT_SECRET') // string

// A fallback for a key the schema leaves optional — used when it's unset
const region = getEnv('S3_REGION', 'eu-west-1') // string, never undefined — ConfigService.get takes the same fallback

The schema in src/env.ts is the one source of truth: loadEnv(envSchema) registers it, and every later loadEnv() / getEnv() reads through it. The cache is sticky: once loadEnv(extendedSchema) has been called, subsequent loadEnv() calls reuse it instead of falling back to the base schema.

getEnv's second argument is a fallback, returned when the value is undefined or null (a 0 or '' is a value). A default every caller shares belongs in the schema (.default('eu-west-1')), where ConfigService and @Value() see it too; the fallback is for one call site that can live without the value.

Passing a schema to getEnv is deprecated

getEnv(key, schema) still reads through the given schema, with a one-time deprecation warning. Register the schema once with loadEnv(envSchema) instead. For a test that needs different values, use withEnv.

createConfigService (deprecated) ​

Earlier versions required createConfigService(envSchema) to get a typed service. That escape hatch still works for back-compat, but it's no longer the recommended path — typed ConfigService covers every use case with less boilerplate. Migrate by:

  1. Putting your schema in src/env.ts (default-exported via defineEnv)
  2. Running kick typegen once (or just kick dev — it auto-runs)
  3. Replacing createConfigService(envSchema) with the bare ConfigService import and dropping the schema argument from your DI wiring

Available Methods ​

MethodReturnDescription
get(key)KickEnv[K] (or T for back-compat)Get a single env variable by key
getAll()Readonly<KickEnv>Get a frozen copy of all config values
reload()voidRe-read .env and re-validate (for HMR)
isProduction()booleanNODE_ENV === 'production'
isDevelopment()booleanNODE_ENV === 'development'
isTest()booleanNODE_ENV === 'test'

@Value Decorator ​

The @Value decorator injects an environment variable directly into a class property. It is evaluated lazily -- the value is read from process.env at access time, not at decoration time.

ts
import { Service, Value, type Env } from '@forinda/kickjs'

@Service()
class MailService {
  @Value('SMTP_HOST', 'localhost')
  private smtpHost!: Env<'SMTP_HOST'>

  @Value('SMTP_PORT', '587')
  private smtpPort!: Env<'SMTP_PORT'>

  @Value('SMTP_API_KEY')
  private apiKey!: Env<'SMTP_API_KEY'> // throws if SMTP_API_KEY is not set
}

When kick typegen has populated the KickEnv global from your src/env.ts, @Value is constrained to known keys (@Value('NOPE') becomes a tsc error) and Env<K> resolves to the schema's inferred type for that key — so Env<'PORT'> is number rather than string. See Type Generation for the full pipeline.

For projects that don't use the env schema, raw string keys still work — @Value falls back to accepting any string when KickEnv is empty.

If no default is provided and the environment variable is missing, accessing the property throws an error to catch misconfiguration early:

@Value('SMTP_API_KEY'): Environment variable "SMTP_API_KEY" is not set and no default was provided.

The container resolves @Value properties during instance creation, alongside @Autowired property injection.

CLI Configuration (kick.config.ts) ​

The kick.config.ts file configures the CLI's code generators, project-local commands, and installable CLI plugins. Key options:

ts
import { defineConfig } from '@forinda/kickjs-cli'

export default defineConfig({
  pattern: 'rest', // 'rest' (default) | 'minimal'
  modules: {
    dir: 'src/modules', // default location (convention) — override freely
    repo: { name: 'postgres' }, // 'inmemory' (built-in) or { name: '<db>' } for a custom stub
    pluralize: false, // true → `kick g module user` makes users/
    pluralizeRoutes: true, // false → mounts at /user instead of /users
    schemaDir: 'src/db/schema', // schema directory (configurable)
  },
  plugins: [], // KickCliPlugin[] — see ./cli-plugins.md
  commands: [], // project-local custom CLI commands
  typegen: {
    disable: [], // skip specific plugin typegens (e.g. ['kick/db'])
  },
})

Disabling individual typegens

kick typegen --list prints every registered plugin id; add any of them to typegen.disable to skip its emission while leaving the rest running. Useful for adopters who hand-write KickDbRegister instead of letting the kick/db plugin generate it. See Typegen → Disabling specific plugin typegens.

Folder paths are conventions

src/modules/, src/db/schema, and the rest of the defaults reflect what kick new scaffolds. Generators read kick.config.ts for the live values, so renaming or relocating directories is a one-line config change — not a fork.

The plugins field expects an array of KickCliPlugin instances (typically built with defineCliPlugin()). Each plugin can contribute commands, register, typegens, and generators — see CLI Plugins for the full shape and conflict semantics.

Deprecated Fields

The following top-level fields are deprecated in favor of the modules block:

  • modulesDir → modules.dir
  • defaultRepo → modules.repo
  • schemaDir → modules.schemaDir
  • pluralize → modules.pluralize

They still work but will be removed in a future major version.

Released under the MIT License. Built with TypeScript — runs on Express, Fastify, or h3.