Configuration and the database layer

12.6.0

Load configuration once, validate required settings on startup, and keep database access in a provider.

On this page

Validate required settings on startup

Install @nestjs/config, then register ConfigModule. A validation function can fail startup when a required setting is missing. Supply DATABASE_URL through the environment and inject ConfigService in the provider that creates the database connection.

import { Module } from "@nestjs/common";
import { ConfigModule } from "@nestjs/config";

@Module({
  imports: [
    ConfigModule.forRoot({
      validate(config) {
        if (!config.DATABASE_URL) throw new Error("DATABASE_URL is required");
        return config;
      },
    }),
  ],
})
export class AppModule {}

Separate HTTP from persistence

Controllers read inputs and give responses. A service runs business rules and calls a repository or database client. Nest can work with a driver or ORM through providers. Keep schema changes in migrations so environments can apply the same changes.

@Injectable()
export class InventoryService {
  constructor(private readonly products: ProductRepository) {}

  availableProducts() {
    return this.products.findWithStock();
  }
}

@Controller("inventory")
export class InventoryController {
  constructor(private readonly inventory: InventoryService) {}

  @Get()
  list() {
    return this.inventory.availableProducts();
  }
}

Official references