loading...
Cover image for How to make your express API more secure with helmet

How to make your express API more secure with helmet

gabrielrufino profile image Gabriel Rufino ・2 min read

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.

Alt Text

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:

Alt Text

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:

Alt Text

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

Posted on by:

gabrielrufino profile

Gabriel Rufino

@gabrielrufino

Fullstack Developer around JavaScript stack. Solving problems, generating value!

Discussion

markdown guide
 

Hi Gabriel, great introduction.

I'm also using Helmet, and have:

app.use(helmet())
app.disable('x-powered-by')
 

Wow,
Lately I heard of using helmet for Dynamic Title/ tags for react app.
Suerly will try it in express

 

great article, i just want to know why and how this headers improve the security of my express app?