0
0
NodejsHow-ToBeginner · 4 min read

How to Use Helmet in Node.js for Secure HTTP Headers

To use helmet in Node.js, first install it with npm install helmet. Then, import it and add app.use(helmet()) in your Express app to enable default security headers.
📐

Syntax

The basic syntax to use helmet in a Node.js Express app involves importing the package and applying it as middleware. This sets various HTTP headers to improve security.

  • const helmet = require('helmet'): Imports the Helmet package.
  • app.use(helmet()): Applies Helmet middleware with default settings.
javascript
const express = require('express');
const helmet = require('helmet');

const app = express();

app.use(helmet());
💻

Example

This example shows a simple Express server using Helmet to add security headers. When you visit the server, Helmet sets headers like Content-Security-Policy and X-DNS-Prefetch-Control automatically.

javascript
import express from 'express';
import helmet from 'helmet';

const app = express();

app.use(helmet());

app.get('/', (req, res) => {
  res.send('Hello, secure world!');
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
Output
Server running on http://localhost:3000
⚠️

Common Pitfalls

Common mistakes when using Helmet include:

  • Not calling app.use(helmet()) before defining routes, so headers are not set.
  • Using outdated Helmet versions that require separate middleware for each header (modern Helmet bundles them).
  • Overriding Helmet headers incorrectly, which can weaken security.

Always use the latest Helmet version and apply it early in your middleware stack.

javascript
/* Wrong way: Helmet applied after routes */
app.get('/', (req, res) => {
  res.send('Hello');
});
app.use(helmet()); // This won't secure the '/' route

/* Right way: Helmet applied before routes */
app.use(helmet());
app.get('/', (req, res) => {
  res.send('Hello');
});
📊

Quick Reference

Helmet sets these common HTTP headers by default:

  • Content-Security-Policy: Controls resources the browser can load.
  • Expect-CT: Helps detect misissued certificates.
  • Referrer-Policy: Controls referrer information sent.
  • Strict-Transport-Security: Enforces HTTPS.
  • X-Content-Type-Options: Prevents MIME sniffing.
  • X-DNS-Prefetch-Control: Controls DNS prefetching.
  • X-Frame-Options: Prevents clickjacking.
  • X-Permitted-Cross-Domain-Policies: Controls Adobe Flash and Acrobat policies.
  • X-XSS-Protection: Enables cross-site scripting filters.

Key Takeaways

Install Helmet with npm and import it in your Node.js app.
Use app.use(helmet()) early to set secure HTTP headers automatically.
Helmet helps protect your app from common web vulnerabilities by setting multiple headers.
Avoid applying Helmet after routes or using outdated versions.
Review Helmet's default headers to understand your app's security posture.