Tuesday, December 2, 2025

thumbnail

Using Helmet for Express Security

Using Helmet for Express Security


Helmet is a widely used middleware for Express.js that helps secure your web application by setting various HTTP security headers.

It protects against common web vulnerabilities such as:


Cross-Site Scripting (XSS)


Clickjacking


Content Sniffing


HTTP Strict Transport Security (HSTS) misconfigurations


Cross-Site Resource Injections (CSP issues)


Helmet does not fix all vulnerabilities, but it makes your app much safer with minimal setup.


๐Ÿš€ 1. Install Helmet


Run the following command:


npm install helmet



Or, if using yarn:


yarn add helmet


๐Ÿ—️ 2. Basic Usage in Express


Add Helmet as middleware:


const express = require('express');

const helmet = require('helmet');


const app = express();


// Use Helmet with default settings

app.use(helmet());


app.get('/', (req, res) => {

  res.send('Hello, world! Secure with Helmet!');

});


app.listen(3000, () => console.log('Server running on port 3000'));



This automatically enables multiple secure headers.


๐Ÿ” 3. What Helmet Protects You From


Helmet sets the following security headers (by default or optionally):


Helmet Middleware Security Header Purpose

helmet.dnsPrefetchControl() X-DNS-Prefetch-Control Prevents DNS prefetching

helmet.frameguard() X-Frame-Options Prevents clickjacking

helmet.hidePoweredBy() Removes X-Powered-By Hides Express fingerprint

helmet.hsts() Strict-Transport-Security Forces HTTPS

helmet.ieNoOpen() X-Download-Options Prevents MS downloads from executing HTML

helmet.noSniff() X-Content-Type-Options Prevents MIME-sniffing

helmet.referrerPolicy() Referrer-Policy Controls referrer header

helmet.xssFilter() X-XSS-Protection Basic XSS mitigation (legacy browsers)


Most headers are automatically enabled when you call helmet().


⚙️ 4. Configuring Helmet


You can customize each security header.


Example: Set a custom Content Security Policy

app.use(

  helmet({

    contentSecurityPolicy: {

      directives: {

        defaultSrc: ["'self'"],

        scriptSrc: ["'self'", "'unsafe-inline'"],

        styleSrc: ["'self'"],

        imgSrc: ["'self'", "data:"],

      },

    },

  })

);



CSP is one of the strongest protections against XSS.


๐ŸŒ 5. Enabling Helmet Submodules Individually


If you want finer control:


app.use(helmet.frameguard({ action: 'deny' }));

app.use(helmet.xssFilter());

app.use(helmet.noSniff());

app.use(helmet.hidePoweredBy());

app.use(helmet.referrerPolicy({ policy: 'no-referrer' }));


๐Ÿ”’ 6. Using HSTS (Strict HTTPS Enforcement)


Only enable HSTS if your site runs fully on HTTPS:


app.use(

  helmet.hsts({

    maxAge: 31536000, // 1 year

    includeSubDomains: true,

    preload: true,

  })

);



This prevents browsers from downgrading to insecure HTTP.


๐Ÿงช 7. Disable Specific Helmet Features


Example: disable contentSecurityPolicy but keep others:


app.use(

  helmet({

    contentSecurityPolicy: false,

  })

);


๐Ÿ› ️ 8. Common Real-World Helmet Config

app.use(

  helmet({

    contentSecurityPolicy: {

      directives: {

        defaultSrc: ["'self'"],

        scriptSrc: ["'self'", "https://trusted-cdn.com"],

        styleSrc: ["'self'", "https://trusted-cdn.com"],

        imgSrc: ["'self'", "data:", "https://images.example.com"],

      },

    },

    referrerPolicy: { policy: 'strict-origin-when-cross-origin' },

  })

);


๐Ÿ“Œ Best Practices with Helmet


Always use HTTPS (especially with HSTS)


Combine Helmet with:


Input validation


Rate limiting


CSRF protection


Secure cookies (httpOnly, secure, SameSite)


Avoid 'unsafe-inline' in CSP unless absolutely necessary


Test CSP before production (can break scripts/styles)


๐Ÿ Conclusion


Helmet is a simple yet powerful tool to enhance your Express app’s security.

By adding secure HTTP headers, it protects against common attacks and enforces safer browser behavior with very little effort.


It’s one of the must-have middlewares for any production Express application.

Learn MERN Stack Training in Hyderabad

Read More

Storing Passwords Securely with bcrypt

Role-Based Access Control in MERN Stack

Preventing XSS & CSRF in MERN

Securing Your MERN Stack App

Visit Our Quality Thought Training Institute in Hyderabad

Get Directions 


Subscribe by Email

Follow Updates Articles from This Blog via Email

No Comments

About

Search This Blog

Powered by Blogger.

Blog Archive