NestJS course · Module 9: Deployment and Infrastructure
SSL/TLS and HTTPS Configuration - the Empire's defensive shield
In this lesson6
Cybersecurity legionary! The password of a legionary logging in travels over café Wi-Fi in plain text, and a foreign site quietly sends requests on his behalf. Architect Vitruvius knows that every province needs fortifications: just as walls protected Rome from invaders, TLS and HTTP safeguards protect a NestJS application from attacks from the network.
SSL (Secure Sockets Layer) and its successor TLS (Transport Layer Security) are cryptographic protocols that ensure secure communication. SSL 2.0 and 3.0 are prohibited today as insecure, and TLS 1.2 and 1.3 are what is used - the name "SSL certificate" stuck out of habit. HTTPS is HTTP running over TLS, which encrypts data between the client and the server. We will build four rings of walls, from transport to application: TLS encrypts the road, Helmet sets security headers, CORS decides which sites may call the API, and rate limiting counts clients' requests.
Generating SSL certificates
The first step is obtaining certificates. In development we can generate self-signed certificates, and in production we use Let's Encrypt or commercial providers.
Development certificates (self-signed)
The script calls openssl through execSync and saves the key and the certificate in the certs directory:
// scripts/generate-dev-cert.ts
import { execSync } from 'node:child_process';
import * as fs from 'node:fs';
import * as path from 'node:path';
// Directory computed from the project directory - ES modules have no __dirname
const certsDir = path.join(process.cwd(), 'certs');
// Create the certificates directory
if (!fs.existsSync(certsDir)) {
fs.mkdirSync(certsDir, { recursive: true });
}
// Generate a private key and a certificate with names in subjectAltName
execSync(`openssl req -x509 -newkey rsa:4096 \
-keyout ${certsDir}/key.pem \
-out ${certsDir}/cert.pem \
-days 365 -nodes \
-subj "/C=PL/ST=Roma/L=Roma/O=Imperium/CN=localhost" \
-addext "subjectAltName=DNS:localhost,IP:127.0.0.1"`);
console.log('Development certificates generated in the certs/ directory');-nodes leaves the key without a passphrase (OpenSSL 3 calls this option -noenc, but the old name also works in LibreSSL on macOS). -addext adds names in the subjectAltName field: browsers have ignored the CN alone for years, so they would reject a certificate without it. We compute the directory from process.cwd(), because a new NestJS 12 project is an ES module, where __dirname does not exist.
HTTPS configuration in NestJS
NestFactory.create() accepts httpsOptions with the key and the certificate:
// src/main.ts - starting the server with HTTPS
import { NestFactory } from '@nestjs/core';
import { NestExpressApplication } from '@nestjs/platform-express';
import { AppModule } from './app.module';
import * as fs from 'node:fs';
import * as path from 'node:path';
async function bootstrap() {
const isProduction = process.env.NODE_ENV === 'production';
// HTTPS options - SSL certificates
const httpsOptions = isProduction
? {
key: fs.readFileSync(process.env.SSL_KEY_PATH),
cert: fs.readFileSync(process.env.SSL_CERT_PATH),
ca: fs.readFileSync(process.env.SSL_CA_PATH), // Certificate chain
}
: {
key: fs.readFileSync(path.join(process.cwd(), 'certs', 'key.pem')),
cert: fs.readFileSync(path.join(process.cwd(), 'certs', 'cert.pem')),
};
const app = await NestFactory.create<NestExpressApplication>(AppModule, { httpsOptions });
// Behind a reverse proxy: trust the X-Forwarded-* headers from the first hop
app.set('trust proxy', 1);
// Force the HTTP -> HTTPS redirect
if (isProduction) {
app.use((req, res, next) => {
if (!req.secure) {
// The address comes from configuration, not from the Host header set by the client
return res.redirect(301, `https://${process.env.PUBLIC_HOST}${req.originalUrl}`);
}
next();
});
}
await app.listen(process.env.PORT || 3000);
}
bootstrap();TLS ends either in Node.js itself (httpsOptions) or in a reverse proxy that forwards traffic over plain HTTP with an X-Forwarded-Proto header. trust proxy tells Express to trust that header, so req.secure works in both models. The first version checked the header alone, and without a proxy it is absent - every request got a redirect and a loop formed. The target address comes from configuration, because the Host header is set by the client.
Helmet.js - HTTP security headers
Helmet is like a centurion's helmet - it protects the head, that is the HTTP headers, from the most common attacks:
// src/main.ts - Helmet configuration
import helmet from 'helmet';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
// Basic Helmet configuration - enough for most APIs:
// app.use(helmet());
// Advanced Helmet configuration (instead of the basic one)
app.use(helmet({
// Content-Security-Policy - controls where resources are loaded from
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'"],
styleSrc: ["'self'", "'unsafe-inline'", 'https://fonts.googleapis.com'],
fontSrc: ["'self'", 'https://fonts.gstatic.com'],
imgSrc: ["'self'", 'data:', 'https:'],
connectSrc: ["'self'", ...(process.env.API_URL ? [process.env.API_URL] : [])],
frameSrc: ["'none'"],
objectSrc: ["'none'"],
},
},
// Strict-Transport-Security - enforces HTTPS
strictTransportSecurity: {
maxAge: 31536000, // 1 year
includeSubDomains: true,
preload: true,
},
// X-Frame-Options - prevents clickjacking
xFrameOptions: { action: 'deny' },
// X-Content-Type-Options - prevents MIME sniffing
xContentTypeOptions: true,
// Referrer-Policy
referrerPolicy: { policy: 'strict-origin-when-cross-origin' },
}));
}The option names come from Helmet 8; the former hsts, frameguard and noSniff are deprecated aliases. 'unsafe-inline' is gone from scriptSrc, because it switched off CSP's protection against XSS. preload puts the domain on the browsers' HSTS list, and that is hard to undo, so enable it deliberately. Since NestJS 12.1 the same default headers are set by the built-in app.useSecurityHeaders().
CORS for production
CORS (Cross-Origin Resource Sharing) controls which domains may talk to our API. It is like the list of the Empire's trusted ambassadors:
// src/main.ts - production CORS configuration
import { CorsOptions } from '@nestjs/common/interfaces/external/cors-options.interface';
const corsOptions: CorsOptions = {
origin: (origin, callback) => {
const allowedOrigins = process.env.CORS_ORIGINS?.split(',') || [];
// Allow requests without an origin (mobile, Postman)
if (!origin) return callback(null, true);
if (allowedOrigins.includes(origin)) {
callback(null, true);
} else {
// false = no CORS headers; the browser blocks the response by itself
callback(null, false);
}
},
methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With'],
exposedHeaders: ['X-Total-Count', 'X-Page-Count'],
credentials: true,
maxAge: 86400, // Cache the preflight for 24h (Chromium caps it at 2h)
};
app.enableCors(corsOptions);A foreign domain simply gets no CORS headers; the first version returned an error, which ended in a 500 response and junk in the logs. CORS protects only browser users - Postman or a mobile app ignore it, so it does not replace authorization.
Rate Limiting with @nestjs/throttler
Rate limiting is the guards at the gates who count how many people enter in a given time:
// src/app.module.ts - ThrottlerModule configuration
import { Module } from '@nestjs/common';
import { ThrottlerModule, ThrottlerGuard } from '@nestjs/throttler';
import { APP_GUARD } from '@nestjs/core';
@Module({
imports: [
ThrottlerModule.forRoot([
{
name: 'short', // Short-term limit
ttl: 1000, // 1 second
limit: 3, // Max 3 requests per second
},
{
name: 'medium', // Medium limit
ttl: 10000, // 10 seconds
limit: 20, // Max 20 requests per 10 seconds
},
{
name: 'long', // Long-term limit
ttl: 60000, // 1 minute
limit: 100, // Max 100 requests per minute
},
]),
],
providers: [
{
provide: APP_GUARD,
useClass: ThrottlerGuard,
},
],
})
export class AppModule {}ttl is given in milliseconds, and all three limits apply at the same time. The throttler protects against brute force and API abuse, but not against a real DDoS, which clogs the link before the traffic reaches Node.js. Behind a proxy set trust proxy, and with several instances use a shared store in Redis.
Decorators change the limits for individual endpoints:
// Disabling rate limiting for specific endpoints
import { SkipThrottle, Throttle } from '@nestjs/throttler';
@Controller('legions')
export class LegionsController {
@SkipThrottle({ short: true, medium: true, long: true }) // No limit for the health check
@Get('health')
healthCheck() {
return { status: 'ok' };
}
@Throttle({ short: { ttl: 1000, limit: 1 } }) // A stricter limit
@Post('login')
login() {
// Login limited to 1 req/s
}
}With named limits, @SkipThrottle() without arguments disables none of them - in the test the health check got a 429 after three requests, which is why we list the names. @Throttle changes only short; medium and long still apply.
CSRF protection
CSRF (Cross-Site Request Forgery) is an attack in which a malicious site makes requests on behalf of a logged-in user. It concerns login with cookies; the browser does not attach a JWT in the Authorization header by itself. Older projects protected themselves with the csurf package:
// src/main.ts - CSRF protection with csurf (deprecated package, for old projects only)
import csurf from 'csurf';
import cookieParser from 'cookie-parser';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
// csurf with the cookie option needs cookie-parser first
app.use(cookieParser());
// CSRF protection (for applications with sessions/cookies)
app.use(csurf({
cookie: {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'strict',
},
}));
// Middleware setting the CSRF token in the response
app.use((req, res, next) => {
res.cookie('XSRF-TOKEN', req.csrfToken(), {
httpOnly: false, // The frontend must be able to read it
secure: process.env.NODE_ENV === 'production',
sameSite: 'strict',
});
next();
});
}csurf is archived and marked as deprecated. It also needs cookie-parser before it - without it every request in the test ended with a 500 error. NestJS 12.1 has built-in protection:
// src/main.ts - built-in CSRF protection (NestJS 12.1+)
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.enableCsrfProtection({
// A frontend on another domain that may send POSTs with cookies
trustedOrigins: ['https://admin.imperium.rome'],
});
await app.listen(3000);
}enableCsrfProtection() checks the Sec-Fetch-Site header that browsers attach to requests. In the test a POST from a foreign site got a 403, while a GET, requests without browser headers and trusted domains went through. The NestJS documentation leaves tokens, e.g. from the csrf-csrf package, for very old browsers.
Complete security configuration
Helmet middleware can also be attached in a module:
// src/security/security.module.ts
import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
import { ThrottlerModule } from '@nestjs/throttler';
import helmet from 'helmet';
@Module({
imports: [
ThrottlerModule.forRoot([
{ name: 'short', ttl: 1000, limit: 3 },
{ name: 'long', ttl: 60000, limit: 100 },
]),
],
})
export class SecurityModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(
helmet(),
helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'"],
},
}),
)
.forRoutes('*');
}
}helmet() already sets a default CSP, and the second call overwrites it - a single call with the contentSecurityPolicy option would be enough.
Security is not a one-off task but a continuous process - like defending the walls, which required constant vigilance from the guards. Every layer (TLS, Helmet, CORS, rate limiting, CSRF) adds another wall. I recommend you start from Helmet's defaults and add exceptions only when something stops working. In the next lesson we will build a CI/CD pipeline that checks these walls on every deployment.
Remember: one wall is never enough - the Empire defends itself with rings, from the road to the gate.
Code for this lesson: src/security-config.ts
// SSL/TLS and HTTPS Configuration - Defensive Shield of the Empire
import { NestFactory } from '@nestjs/core';
import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
import { ThrottlerModule, ThrottlerGuard } from '@nestjs/throttler';
import { APP_GUARD } from '@nestjs/core';
import helmet from 'helmet';
import * as fs from 'fs';
// 1. HTTPS Configuration
async function bootstrap() {
const httpsOptions = {
key: fs.readFileSync(process.env.SSL_KEY_PATH),
cert: fs.readFileSync(process.env.SSL_CERT_PATH),
};
// TODO: Create the application with httpsOptions
// const app = await NestFactory.create(AppModule, { httpsOptions });
// 2. Helmet - security headers
// app.use(helmet({
// contentSecurityPolicy: {
// directives: {
// defaultSrc: ["'self'"],
// scriptSrc: ["'self'"],
// },
// },
// hsts: { maxAge: 31536000, includeSubDomains: true },
// frameguard: { action: 'deny' },
// }));
// 3. CORS for production
// app.enableCors({
// origin: process.env.CORS_ORIGINS?.split(','),
// methods: ['GET', 'POST', 'PUT', 'DELETE'],
// credentials: true,
// });
}
// 4. Rate Limiting with @nestjs/throttler
@Module({
imports: [
ThrottlerModule.forRoot([
{ name: 'short', ttl: 1000, limit: 3 },
{ name: 'long', ttl: 60000, limit: 100 },
]),
],
providers: [
{ provide: APP_GUARD, useClass: ThrottlerGuard },
],
})
export class SecurityModule {}
// TODO: Add Helmet middleware to SecurityModule
// TODO: Configure CORS with a list of allowed domains
// TODO: Add CSRF protection for endpoints that use cookies
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. Helmet.js in a NestJS application is used for:
2. @nestjs/throttler in NestJS is used for:
These are 2 of 3 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Code editor
Implement SecurityModule with ThrottlerModule, Helmet middleware, and CORS configuration
- Vertical ordering
Arrange the NestJS application security layers from lowest (transport) to highest (application):