Search…
Config

Nest Config

Wraps Nest's Configuration functionality with the following functionality:
  • Validate that required environment variables are set.
  • Support fallback values for local development.
  • Support configurations that is disabled behind Server Side Feature Flags.
  • Helpers for JSON encoded environment variables.
  • Validation, transformation and TypeScript types with Zod.
This configuration system should replace NX's environment files as the primary way to configure Nest modules in our APIs. This is especially useful as we create bigger and deeper module trees.

Basic usage

First you define a configuration and a load function.
1
import { defineConfig } from '@island.is/nest/config'
2
3
export const someModuleConfig = defineConfig({
4
name: 'SomeModule',
5
load: (env) => ({
6
url: env.required('SOME_MODULE_URL', 'http://localhost:3000'),
7
secret: env.required('SOME_MODULE_SECRET'),
8
ttl: env.optionalJSON('SOME_MODULE_TTL') ?? 60,
9
}),
10
})
Copied!
These configuration definitions should ideally mirror config blocks in our Helm DSL.
The env object has helpers to read values from the environment:
1
interface EnvLoader {
2
required(envVariable: string, devFallback?: string): string
3
requiredJSON<T = any>(envVariable: string, devFallback?: T): T
4
optional(envVariable: string, devFallback?: string): string | undefined
5
optionalJSON<T = any>(envVariable: string, devFallback?: T): T | undefined
6
}
Copied!
These helpers have the following behaviour:
  • The required helpers are designed for everything that needs to be configured in production. If something is missing, its behaviour depends on NODE_ENV:
    • In production, it crashes the process after logging something like this: SomeModule is not configured. Missing environment variables: SOME_MODULE_URL, SOME_MODULE_SECRET
    • In development, it returns the devFallback argument. If there is no devFallback specified, it logs a warning and keeps running with a partial configuration (isConfigured === false).
  • The optional helpers are designed for optional configuration which you might have good defaults for.
    • If you want the same default value in dev and production, just do this: env.optional('EMAIL') ?? '[email protected]'.
    • If you want different defaults or don't want any default value in production, you can use the devFallback argument: env.optional('CACHE_URL', 'localhost:1122')
  • The *JSON variants try to parse the environment variable as JSON. This is very handy for boolean/numerical environment variables or more complex configuration. If you ever use these helpers, you should specify the expected types using the Zod schema. Any JSON parsing issues are logged as error before crashing the process (with requiredJSON).

Injecting module config

After defining the config, you can inject it into services using its key. By using the ConfigType interface you get a strongly typed configuration object.
1
import { Inject } from '@nestjs/common'
2
import { ConfigType } from '@island.is/nest/config'
3
import { someModuleConfig } from './someModule.config'
4
5
export class SomeModuleService {
6
constructor(
7
@Inject(someModuleConfig.KEY)
8
private config: ConfigType<typeof someModuleConfig>,
9
) {
10
config.isConfigured // boolean
11
config.url // string
12
config.secret // string
13
config.ttl // number
14
}
15
}
Copied!

Loading a module and it's configuration

Loading configuration happens through the root module like in NestJS's Config module.
1
import { ConfigModule } from '@island.is/nest/config'
2
import { SomeModuleModule, someModuleConfig } from '@island.is/some/module'
3
4
@Module({
5
imports: [
6
ConfigModule.forRoot({
7
load: [
8
someModuleConfig,
9
// ...
10
],
11
}),
12
SomeModuleModule,
13
// ...
14
],
15
})
16
export class SomeAppModule {}
Copied!
In this example the module is configured and imported in the same place. In many cases, the module's configuration will be loaded in the root module but imported elsewhere. For example, a hypothetical IdsModule may be imported in multiple places, all sharing a singleton configuration and services.
By listing configuration to load in the root module, it provides a good overview of all of the modules which are configured and used by the app. Devs and devops can navigate through the config definitions to see which environment variables are needed by each.
If someone accidentally imports a module which is not configured, then NestJS stops the process with an error message specifying the missing configuration.

Validating configuration

Beside validating missing environment variables with the env.required helpers, you can provide a Zod schema which validates the final object.
1
import { defineConfig } from '@island.is/nest/config'
2
import * as z from 'zod'
3
4
const SomeModuleConfig = z.shape({
5
url: z.string().url(),
6
secret: z.string(),
7
ttl: z.number().int().optional(),
8
})
9
10
export const someModuleConfig = defineConfig({
11
name: 'SomeModule',
12
schema: SomeModuleConfig,
13
load: (env) => ({
14
url: env.required('SOME_MODULE_URL', 'http://localhost:3000'),
15
secret: env.required('SOME_MODULE_SECRET'),
16
ttl: env.optionalJSON('SOME_MODULE_TTL') ?? 60,
17
}),
18
})
Copied!
This is especially useful for a few things:
  • Validate that configuration values are valid (urls, regex, etc).
  • Validate the type of values parsed by the *JSON helpers.
  • Provide better TypeScript types for values parsed by the *JSON helpers.
If configuration validation fails then the process is stopped with an error similar to this:
1
SomeModule is not configured. Validation failed with the following errors:
2
* url is not a string.
3
* ttl is not a number.
Copied!

Advanced functionality

Server side features

If you're working on server-side functionality or integrations which needs to be on main, but it's not ready for staging or production, you can use Server-Side Feature Flags to disable the functionality. In these cases, entire module configurations may be missing which would crash configuration loading.
To handle this, you can define a configuration to depend on a specific server side feature:
1
import { defineConfig } from '@island.is/nest/config'
2
3
const EXTERNAL_CLIENT_FEATURE = 'EXTERNAL_CLIENT'
4
5
export const someModuleConfig = defineConfig({
6
name: 'ExternalClient',
7
serverSideFeature: EXTERNAL_CLIENT_FEATURE,
8
load: (env) => ({
9
url: env.required('EXTERNAL_CLIENT_URL'),
10
}),
11
})
Copied!
When serverSideFeature is set, the config module is only loaded if the specified feature is turned on. Alternatively, the configuration object only has its isConfigured attribute set to false.

Supporting dynamic configuration

It is possible to support both global configuration as well as dynamic configuration. Then we use our own injection key:
1
// Snip
2
3
export const someModuleConfig = defineConfig({
4
// Snip
5
})
6
7
// New:
8
export const SomeModuleConfigKey = 'SomeModuleConfigKey'
Copied!
1
import { Inject } from '@nestjs/common'
2
import { ConfigType } from '@island.is/nest/config'
3
import { someModuleConfig, SomeModuleConfigKey } from './someModule.config'
4
5
export class SomeModuleService {
6
constructor(
7
@Inject(SomeModuleConfigKey)
8
private config: ConfigType<typeof someModuleConfig>,
9
) {}
10
}
Copied!
The module can then provide the injection key using existing global configuration, as well as support a dynamic module registration with an explicit config object:
1
@Module({
2
providers: [
3
SomeModuleService,
4
{ provide: SomeModuleConfigKey, useExisting: featureFlagsConfig.KEY },
5
],
6
exports: [SomeModuleService],
7
})
8
export class SomeModuleModule {
9
static register(config: ConfigType<typeof featureFlagsConfig>) {
10
return {
11
module: SomeModuleModule,
12
providers: [{ provide: SomeModuleConfigKey, useValue: config }],
13
}
14
}
15
}
Copied!
To import a module with dynamic configuration, just call the register static function:
1
import { ConfigModule } from '@island.is/nest/config'
2
import { SomeModuleModule, someModuleConfig } from '@island.is/some/module'
3
4
@Module({
5
imports: [
6
SomeModuleModule.register({
7
host: '',
8
secret: '',
9
}),
10
// ...
11
],
12
})
13
export class SomeAppModule {}
Copied!

Running unit tests

Run nx test nest-config to execute the unit tests via Jest.
Last modified 8d ago