Configuration: @nestjs/config and .env
Some values differ between your computer and the server: the port, the database path, the secret key for tokens. They are not written in the code but kept in environment variables. The @nestjs/config module reads them from a .env file and provides them through the ConfigService service.
Installation and the .env file
npm i @nestjs/configCreate a .env file in the project root, next to package.json:
PORT=3000
DB_PATH=blog.sqlite
JWT_SECRET=change-me-to-a-long-random-stringEach line is a variable name, an equals sign and a value. No quotes are needed.
Connecting the module
// src/app.module.ts
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { PostsModule } from './posts/posts.module';
@Module({
imports: [ConfigModule.forRoot({ isGlobal: true }), PostsModule],
})
export class AppModule {}ConfigModule.forRoot() reads .env at startup and adds the values to process.env. The isGlobal: true option makes ConfigService available in every module without a separate import.
Reading settings
ConfigService is injected like any service:
// src/app.controller.ts
import { Controller, Get } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
@Controller()
export class AppController {
constructor(private readonly config: ConfigService) {}
@Get('health')
health() {
return { status: 'ok', database: this.config.get<string>('DB_PATH') };
}
}Open http://localhost:3000/health — you get {"status":"ok","database":"blog.sqlite"}. get() returns undefined if the variable is missing; the second argument sets a default: get('PORT', 3000).
For required settings there is getOrThrow(): if the variable is missing, the application fails right away with a clear error instead of breaking later.
// src/auth/auth.service.ts
const secret = this.config.getOrThrow<string>('JWT_SECRET');The port in main.ts
In src/main.ts the service is taken from the application with app.get():
// src/main.ts
import { ConfigService } from '@nestjs/config';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const config = app.get(ConfigService);
await app.listen(config.get('PORT', 3000));
}
bootstrap();Where values come from
| Source | Priority |
|---|---|
| System environment variables | Higher |
The .env file | Lower |
The default in get() | If found nowhere |
So on a server you may skip the .env file and set variables through the hosting tools instead. All values from .env are strings: PORT arrives as "3000".
Common mistake
The .env file with passwords and keys ends up in Git. Check that .env is listed in .gitignore — a new NestJS project may not have it. For other developers, keep a .env.example file in the repository with the same variable names but no real values.