0
0
ExpressHow-ToBeginner · 4 min read

How to Use Helmet in Express for Security Headers

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

Syntax

The basic syntax to use Helmet in an Express app is simple:

  • import helmet from 'helmet': Imports the Helmet middleware.
  • app.use(helmet()): Adds Helmet to your Express app to set multiple security headers 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)
💻

Example

This example shows a complete Express server using Helmet to add security headers. When you visit the root URL, it responds with a simple message and 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 installing Helmet before importing it, causing errors.
  • Forgetting to call app.use(helmet()), so no headers are set.
  • Using Helmet middleware after routes, which means headers won't apply to those routes.
  • Overriding Helmet headers unintentionally by other middleware or manual header settings.
javascript
import express from 'express'
import helmet from 'helmet'

const app = express()

// Wrong: Helmet used after routes
app.get('/', (req, res) => {
  res.send('Hello, insecure world!')
})

app.use(helmet()) // This won't affect the above route

// Correct: Use Helmet before routes
// app.use(helmet())
// app.get('/', (req, res) => {
//   res.send('Hello, secure world!')
// })
📊

Quick Reference

Helmet sets many HTTP headers to improve security. Here are some common ones it manages:

HeaderPurpose
Content-Security-PolicyControls resources the browser is allowed to load
X-DNS-Prefetch-ControlControls DNS prefetching to improve privacy
X-Frame-OptionsPrevents clickjacking by controlling iframe embedding
Strict-Transport-SecurityEnforces secure (HTTPS) connections to the server
X-Content-Type-OptionsPrevents MIME-sniffing to reduce exposure to drive-by downloads
Referrer-PolicyControls information sent in the Referer header

Key Takeaways

Install Helmet with npm and import it in your Express app.
Use app.use(helmet()) before defining routes to enable security headers.
Helmet sets multiple HTTP headers that protect your app from common attacks.
Avoid placing Helmet middleware after routes or other middleware that override headers.
Check Helmet's documentation to customize headers if needed.