Security is a serious matter! Are you concerned about the security of your APIs?
When it comes to APIs built with Express.js, one simple step can help you increase the level of security on your system: the Helmet library.
What is the Helmet?
Helmet
is a library for Express.js that aggregates 12 simple middleware, responsible for setting some headers in HTTP responses.
Let's do a simple example below:
Simple example
$ mkdir my-api
$ cd my-api
$ npm init -y
$ npm install express --save
Create a file index.js
:
const express = require('express')
const app = express()
app.get('/', (request, response) => {
return response.json({
api: 'live'
})
})
app.listen(3000)
Start the server:
$ node index.js
Notice the headers returned by the request without using the helmet:
We will include the helmet in our API. First, install the package:
$ npm install helmet --save
Import and include in the express app as follows:
const express = require('express')
const helmet = require('helmet')
const app = express()
app.use(helmet())
app.get('/', (request, response) => {
return response.json({
api: 'live'
})
})
app.listen(3000)
Restart the server:
$ node index.js
Discover the new headers defined by the helmet:
These headers add the extra level of security to your API. For example, Strict-Transport-Security
, which allows a website to inform browsers that it should be accessed only over HTTPS, instead of using HTTP.
Some middlewares are enabled by default, others are not. Learn more at https://helmetjs.github.io/
See you soon
Top comments (7)
Hi Gabriel, great introduction.
I'm also using Helmet, and have:
Did you know that the helmet already deactivates the x-powered-by header? Thank you for your feedback bro :D
It could be that I'm using a version that didn't do it by default.
Wow,
Lately I heard of using helmet for Dynamic Title/ tags for react app.
Suerly will try it in express
Interesting!! Thankss
great article, i just want to know why and how this headers improve the security of my express app?
You can read about these headers and how each of these increases a security level to your application. Thank you :D