CodePark/ questions / Configuration & lifecycle hooks
START PRACTICINGPRACTICE
Backend question · NestJS › Configuration & lifecycle hooks

How do you validate environment variables at startup so the app refuses to boot with bad config?

ConfigModule.forRoot({
  validationSchema: Joi.object({
    NODE_ENV: Joi.string().valid("development", "production", "test").default("development"),
    PORT: Joi.number().port().default(3000),
    DATABASE_URL: Joi.string().uri().required(),
  }),
});

Give ConfigModule.forRoot() a validationSchema, usually a Joi object. Joi is a validation library.

At startup (bootstrap), Nest validates the environment with this schema. It throws if a required variable is missing or has the wrong format. So the process exits at once, instead of failing later on the first database call. Joi also applies default values and converts types. For example, PORT becomes a number.

The alternative is a custom validate(config) function. A common pattern:

  • Define a class with class-validator decorators.
  • Convert the raw config into that class with plainToInstance.
  • Run validateSync.
  • Throw if there are errors.

Either way, failing fast at startup turns a confusing runtime error into a clear error at deploy time.

  • Pass a Joi validationSchema to ConfigModule.forRoot().
  • Or write a custom validate() function with class-validator.
  • Validation runs at startup and throws on invalid config.
  • Joi can apply defaults and convert types.
  • Failing fast at startup is better than breaking at runtime.