Introduction
Security is an important part of building web applications with Node.js. An application may work correctly, but without appropriate security settings, it can still be exposed to risks such as clickjacking, certain cross-site scripting (XSS) attacks, and unsafe resource loading.
Helmet.js is a middleware package for Express.js that helps improve web application security by setting various HTTP response headers. These headers tell browsers how to handle resources and apply certain security restrictions.
For example, Helmet can configure headers that help prevent a website from being embedded in an unauthorized frame, reduce MIME-type sniffing, and control which resources a browser is allowed to load.
In this tutorial, you will learn what Helmet is, why it is used in Node.js, how to install and configure it in Express.js, and how to apply security headers using practical examples.
What Is Helmet in Node.js?
Helmet is a security middleware package commonly used with Express.js applications. It sets HTTP response headers that help protect web applications against some common browser-based threats.
HTTP response headers provide instructions and metadata to the browser. Helmet configures a collection of security-related headers using its middleware.
Some examples include:
- Content-Security-Policy (CSP): Controls which sources the browser may load certain resources from.
- X-Content-Type-Options: Helps prevent browsers from interpreting files as a different content type.
- Strict-Transport-Security (HSTS): Tells browsers to use HTTPS for future requests to a site.
- X-Frame-Options: Controls whether a page can be displayed inside a frame.
- Referrer-Policy: Controls how much referrer information browsers send with requests.
The exact headers Helmet sets depend on the version and configuration. Helmet does not replace authentication, authorization, input validation, or other application security measures.
Why Is Helmet Used in Node.js?
Helmet helps developers apply useful browser security headers without manually configuring each header separately.
1. Improve Browser Security
Helmet configures headers that can reduce exposure to certain browser-based attacks.
2. Reduce Clickjacking Risks
Headers such as X-Frame-Options and CSP’s frame-ancestors directive can restrict whether another website is allowed to embed your pages in a frame.
3. Help Control Resource Loading
Content Security Policy can restrict the origins from which scripts, styles, images, and other resources may load.
4. Prevent MIME-Type Sniffing
The X-Content-Type-Options: nosniff header helps prevent browsers from guessing a resource’s content type in certain situations.
5. Simplify Security Configuration
Instead of implementing every header manually, you can use Helmet middleware to apply a baseline configuration and customize it for your application.
How Does Helmet Work?
Helmet runs as middleware in an Express.js request-response cycle.
The process generally works like this:
- A client sends a request to the Node.js application.
- Express passes the request through its configured middleware.
- Helmet adds the configured security headers to the response.
- The application processes the request and sends the response.
- The browser receives the response and applies the relevant security policies.
For example, when Helmet sets X-Content-Type-Options: nosniff, the browser receives that header with the response and applies the associated content-type handling rules.
Helmet does not inspect every possible vulnerability in your application. Its main purpose is to configure security-related HTTP response headers.
How to Install Helmet in Node.js
Let’s create a simple Express.js application and add Helmet.
Step 1: Create a Node.js Project
Open a terminal and run:
mkdir nodejs-helmet-example
cd nodejs-helmet-example
npm init -y
These commands create a project directory and initialize a package.json file.
Step 2: Install Express and Helmet
Run the following command:
npm install express helmet
The packages serve these purposes:
- express: Creates the web server and manages routes.
- helmet: Adds security-related HTTP response headers.
Step 3: Create an Express Server
Create a file named server.js:
Create a file named server.js:
const express = require('express');
const helmet = require('helmet');
const app = express();
// Add security headers
app.use(helmet());
app.get('/', (req, res) => {
res.send('Node.js application secured with Helmet');
});
app.get('/api/users', (req, res) => {
res.json([
{ id: 1, name: 'John' },
{ id: 2, name: 'Sarah' }
]);
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
In this example, app.use(helmet()) registers Helmet as application-wide middleware. It applies Helmet’s default header configuration to responses generated by the application.
Step 4: Run the Application
Start the server:
node server.js
Open this URL in your browser:
http://localhost:3000
You should see:
Node.js application secured with Helmet
The response will also include the security headers configured by Helmet.
For this basic setup, you do not need to configure each header individually to get started.
Important Security Headers in Helmet
Helmet configures multiple headers. Here are some important ones and what they do.
1. Content-Security-Policy (CSP)
Content Security Policy controls which sources the browser is allowed to use for certain types of resources.
For example, it can restrict scripts to the same origin as the website.
A simplified policy might look like this:
Content-Security-Policy: default-src 'self'; script-src 'self'
This policy sets a default source of the site’s own origin and restricts script loading to that origin.
Helmet enables CSP by default, but its default policy may require adjustments depending on your frontend. If your application uses inline scripts, external CDNs, analytics tools, or other third-party resources, test and configure the policy carefully.
Avoid adding ‘unsafe-inline’ or ‘unsafe-eval’ merely to make errors disappear, because these directives can weaken CSP protection.
2. X-Content-Type-Options
This header helps prevent browsers from interpreting a resource as a different content type from the one declared by the server.
Example:
X-Content-Type-Options: nosniff
Helmet sets this header by default.
It is especially useful when serving files with correctly configured content types, but it does not replace proper file validation or upload security.
3. Strict-Transport-Security (HSTS)
HSTS tells browsers to use HTTPS for future connections to a site after the browser has received the policy over a secure connection.
Example:
Strict-Transport-Security: max-age=31536000
The max-age value is measured in seconds. Here, it represents one year.
HSTS should be enabled only after HTTPS is configured correctly for the relevant domain. Be cautious with options such as includeSubDomains and preload, because they can affect many subdomains and may be difficult to reverse quickly.
4. X-Frame-Options
This header helps control whether a page can be displayed inside a frame.
Example:
X-Frame-Options: SAMEORIGIN
SAMEORIGIN allows framing by pages from the same origin, while DENY disallows framing entirely.
Helmet’s default configuration uses a restrictive frame policy. If your application intentionally embeds pages in frames, review the requirements and configure a suitable policy. CSP’s frame-ancestors directive is the more flexible modern option.
5. Referrer-Policy
The Referrer-Policy header controls how much referrer information a browser includes when navigating or requesting resources.
For example:
Referrer-Policy: no-referrer
This setting tells the browser not to send referrer information.
Helmet sets a referrer policy by default. The right policy depends on whether your application needs referrer information for analytics or other features.
Customize Helmet Configuration
Although app.use(helmet()) is a useful starting point, applications often need custom settings.
For example, you may want to configure the Content Security Policy explicitly.
const express = require('express');
const helmet = require('helmet');
const app = express();
app.use(
helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'"],
styleSrc: ["'self'"],
imgSrc: ["'self'", 'data:'],
objectSrc: ["'none'"],
frameAncestors: ["'none'"]
}
}
})
);
app.get('/', (req, res) => {
res.send('Custom Helmet configuration');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
This example sets a restrictive CSP that permits same-origin scripts and styles, same-origin images and data URLs, disallows plugin objects, and prevents the page from being embedded in frames.
Important: This policy is illustrative. It may break applications that depend on inline scripts, external stylesheets, fonts, image CDNs, payment widgets, or other third-party resources. Adjust the directives to match your actual application, and test the policy before deploying it.
Disable a Helmet Feature When Necessary
Some applications need to disable or change a specific header because of their architecture.
For example, you can disable Helmet’s Content Security Policy middleware:
app.use(
helmet({
contentSecurityPolicy: false
})
);
This disables CSP configuration by Helmet; other Helmet protections remain enabled according to the other options.
Disabling a security feature should be a deliberate decision. If CSP causes a problem, first inspect the browser console and determine which resources are being blocked. A tailored policy is generally preferable to removing CSP without an alternative.
Using Helmet with Express.js Routes
Helmet is normally registered before routes so that its headers apply consistently to responses.
const express = require('express');
const helmet = require('helmet');
const app = express();
app.use(helmet());
app.use(express.json());
app.get('/api/products', (req, res) => {
res.json([
{ id: 1, name: 'Laptop' },
{ id: 2, name: 'Keyboard' }
]);
});
app.post('/api/products', (req, res) => {
res.status(201).json({
message: 'Product endpoint reached',
product: req.body
});
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
In this example, Helmet runs before the JSON parser and the route handlers. This is a common arrangement because it applies the configured headers to responses generated later in the middleware chain.
The POST route is only a demonstration; a real product-creation endpoint should validate the input and enforce appropriate authentication and authorization.
How to Check Helmet Security Headers
After adding Helmet, you can inspect the HTTP response headers to confirm what your application sends.
Start the server:
node server.js
Then run:
curl -I http://localhost:3000
The command displays response headers. Depending on your Helmet version and configuration, you may see headers such as:
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
Referrer-Policy: no-referrer
Content-Security-Policy: ...
The exact values and headers may vary based on your configuration and Helmet version.
You can also open your browser’s developer tools, select the Network tab, reload the page, select the document request, and inspect the Response Headers section.
If a header is missing, check your middleware order, route-specific behavior, reverse proxy, and any hosting platform that may modify response headers.
Helmet Best Practices for Production
Follow these practices when using Helmet in a production application.
1. Enable Helmet Early
Register Helmet before your routes and other middleware that may send responses, so its headers are applied consistently.
2. Configure CSP for Your Application
Start with a restrictive policy and adjust it to the actual resources your site needs. Consider testing CSP in report-only mode before enforcing a major policy on an existing website.
3. Use HTTPS in Production
Configure TLS correctly and review HSTS settings only when HTTPS is reliably available. Be especially careful with subdomain-wide or preload settings.
4. Test Third-Party Resources
Analytics scripts, fonts, embedded videos, payment tools, and content delivery networks may be blocked by a restrictive CSP. Test the entire application after changing the policy.
5. Keep Helmet Updated
Use a maintained version of Helmet and update dependencies regularly. Review changes to defaults when upgrading.
6. Do Not Depend on Helmet Alone
Helmet is one part of application security. You should also implement authentication, authorization, input validation, safe database queries, secure session handling, rate limiting, and appropriate error handling.
7. Review Headers Added by Proxies
Reverse proxies, CDNs, and hosting platforms may add or override headers. Inspect the headers from the deployed application, not just the local development server.
Common Mistakes When Using Helmet
Avoid these common mistakes:
- Assuming Helmet makes the application completely secure: It configures security headers but does not fix all application vulnerabilities.
- Using a strict CSP without testing: Required scripts, fonts, images, or styles may stop loading.
- Disabling CSP to fix errors: Investigate the blocked resources and configure the policy appropriately.
- Enabling HSTS before HTTPS is ready: Browsers may continue trying to use HTTPS after receiving an HSTS policy.
- Expecting the same headers in every version: Helmet’s defaults can change between releases or with configuration.
- Registering middleware too late: Some responses may bypass Helmet if earlier middleware sends them first.
- Ignoring production infrastructure: A proxy or CDN may change the headers your application sends.
Conclusion
Helmet is a useful security middleware package for Node.js applications built with Express.js. It helps configure HTTP response headers that improve browser security, including policies for content loading, framing, MIME-type handling, and HTTPS behavior.
You can begin with app.use(helmet()) and customize individual features according to your application’s needs. For production use, test security policies carefully, configure HTTPS correctly, keep dependencies updated, and combine Helmet with other application security measures.
By using Helmet thoughtfully, you can establish a stronger security baseline for your Express.js application without manually configuring every response header.