DEV Community

karoon sillapapan
karoon sillapapan

Posted on

NestJS Environment Configuration

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
Enter fullscreen mode Exit fullscreen mode

๐Ÿ“„ 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
Enter fullscreen mode Exit fullscreen mode

โš™๏ธ 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 {}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ“ 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"
  }
}
Enter fullscreen mode Exit fullscreen mode

๐ŸŽฎ 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');
  }
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿš€ 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
Enter fullscreen mode Exit fullscreen mode

๐Ÿ” 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')
  };
}
Enter fullscreen mode Exit fullscreen mode

โœ… 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)
Enter fullscreen mode Exit fullscreen mode

๐Ÿณ 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"]
Enter fullscreen mode Exit fullscreen mode
# 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
Enter fullscreen mode Exit fullscreen mode

๐Ÿ› ๏ธ Best Practices

  1. Use .env for production (default behavior)
  2. Set NODE_ENV in scripts for other environments
  3. Use ConfigService to access environment variables
  4. Check console output to verify which environment is loaded
  5. 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)