Helmet
- Node.js course
- Advanced
- Lesson 19/83
- 5 min
Learn HTTP security headers with the helmet middleware.
What is Helmet?
Helmet is a middleware that sets security HTTP headers for Express apps. It enables many headers in a single call: X-Content-Type-Options, X-Frame-Options, Strict-Transport-Security and more.
These headers protect the browser from abuse. For example X-Frame-Options stops your page from being embedded in an iframe (clickjacking). To install Helmet run npm install helmet; to use it write app.use(helmet()).
The helmet() middleware
Wiring Helmet into Express is easy. First import it with const helmet = require("helmet"), then apply it with app.use(helmet()). You must call it before any routes; otherwise headers may be missing from some responses.
Helmet also lets you control individual headers. For example helmet.contentSecurityPolicy({ directives: { ... } }) customizes the CSP policy. The defaults are good enough for most apps; but reviewing CSP in production is a good habit.
Practice Log the type of helmet
Import the helmet module. Log typeof helmet.
Starter code
// import the module
// log its typeSample solution
const helmet = require("helmet");
console.log(typeof helmet);Expected output
function
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does Helmet do?
- Encrypts the database
- Sets security headers Correct answer
- Increases network speed
- Compresses files
Explanation: Helmet sets security headers.
2 Complete the module name
const helmet = require("____")
const helmet = require("helmet")
Explanation: The Helmet module loads as 'helmet'.
3 Match each piece to its role
| Term | Meaning |
|---|---|
helmet |
Security headers |
app.use(helmet()) |
Enables protection |
X-Frame-Options |
Clickjacking guard |
X-Content-Type-Options |
MIME guard |