Simple environment setup using NestJS built-in features - no custom code needed.
๐ฏ How It Works
NestJS automatically loads environment files based on NODE_ENV
:
NODE_ENV | File Loaded | When |
---|---|---|
(not set) | .env |
Default (Production) |
development |
.env.development |
Development |
uat |
.env.uat |
UAT |
production |
.env |
Production |
๐ File Structure
backend/
โโโ .env # Production (default)
โโโ .env.development # Development
โโโ .env.uat # UAT
โโโ src/app.module.ts
๐ Environment Files
# .env (production - default)
DATABASE_URL=postgresql://user:pass@prod-db:5432/myapp
PORT=3000
# .env.development
DATABASE_URL=postgresql://user:pass@localhost:5432/myapp_dev
PORT=3000
# .env.uat
DATABASE_URL=postgresql://user:pass@uat-db:5432/myapp_uat
PORT=3000
โ๏ธ App Module Setup
// src/app.module.ts
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
envFilePath: [
`.env.${process.env.NODE_ENV}`,
'.env'
],
}),
],
})
export class AppModule {}
๐ Package.json Scripts
{
"scripts": {
"start": "nest start",
"start:dev": "NODE_ENV=development nest start --watch",
"start:uat": "NODE_ENV=uat nest start",
"start:prod": "NODE_ENV=production node dist/main",
"build": "nest build"
}
}
๐ฎ Usage in Code
// In any controller or service
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
@Injectable()
export class AppService {
constructor(private config: ConfigService) {}
getDatabaseUrl(): string {
return this.config.get('DATABASE_URL');
}
getPort(): number {
return this.config.get('PORT');
}
}
๐ Commands
# Development
npm run start:dev
# Loads: .env.development
# UAT
npm run start:uat
# Loads: .env.uat
# Production
npm run start:prod
# Loads: .env
# Default (same as production)
npm start
# Loads: .env
๐ Check Environment
// In main.ts or any file
console.log('NODE_ENV:', process.env.NODE_ENV || 'default');
console.log('Database:', process.env.DATABASE_URL);
// In controller
@Get('health')
getHealth() {
return {
environment: process.env.NODE_ENV || 'default',
database: this.config.get('DATABASE_URL')
};
}
โ Default Behavior
Important: If you don't set NODE_ENV
, NestJS uses .env
file (production).
# These commands do the same thing:
npm start # Uses .env (default)
NODE_ENV=production npm start # Uses .env (explicit)
๐ณ Docker
# Dockerfile
FROM node:18-alpine
ARG NODE_ENV=production
ENV NODE_ENV=${NODE_ENV}
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
RUN npm run build
EXPOSE 3000
CMD ["npm", "run", "start:prod"]
# Build for different environments
docker build -t myapp:dev --build-arg NODE_ENV=development .
docker build -t myapp:uat --build-arg NODE_ENV=uat .
docker build -t myapp:prod . # Uses production by default
๐ ๏ธ Best Practices
- Use .env for production (default behavior)
- Set NODE_ENV in scripts for other environments
- Use ConfigService to access environment variables
- Check console output to verify which environment is loaded
- Never commit sensitive data - use .env.local for secrets
๐จ Troubleshooting
Problem | Solution |
---|---|
Variables not loading | Check file name: .env.development not .env.dev
|
Wrong environment | Check NODE_ENV value in console |
Missing variables | Verify variable exists in correct env file |
Default not working | Remember: no NODE_ENV = .env file |
That's it! NestJS handles everything automatically - just set NODE_ENV
and go!
Top comments (0)