Security Headers
Security headers help protect your NestJS application from common vulnerabilities such as cross-site scripting (XSS), clickjacking, and other attacks. This guide shows how to add recommended security headers to your NestJS app.
Step 1: Why Use Security Headers?
Security headers enhance the protection of your web application by:
- Enforcing HTTPS connections.
- Preventing your app from being embedded in iframes.
- Ensuring proper MIME type handling.
- Controlling referrer information.
Step 2: Install Helmet Middleware
Helmet is a popular middleware for setting security headers in Node.js applications.
-
Install Helmet:
-
Enable Helmet in your NestJS application by modifying
main.ts:
Step 3: Add Custom Security Headers
Helmet allows you to configure custom security headers. Update main.ts to include the following configuration:
Step 4: Explanation of Headers
-
Strict-Transport-Security (HSTS):
- Forces all connections to use HTTPS.
- Configuration:
- max-age=31536000: Enforce HTTPS for 1 year.
- includeSubDomains: Apply this rule to all subdomains.
- preload: Adds the domain to the HSTS preload list.
-
X-Frame-Options:
- Prevents the site from being embedded in iframes.
- Value:
DENY.
-
X-Content-Type-Options:
- Prevents browsers from interpreting files as a different MIME type.
- Value:
nosniff.
-
Referrer-Policy:
- Controls the information sent in the
Refererheader. - Value:
strict-origin-when-cross-origin.
- Controls the information sent in the
Step 5: Test Your Headers
-
Run Your App: Start the NestJS application:
-
Inspect the Headers: Use browser developer tools or tools like Postman to verify that the headers are applied.
Congratulations!
You’ve successfully added security headers to your NestJS application, enhancing its security against various attacks. 🎉