Algobook
- The developer's handbook
mode-switch
back-button
Buy Me A Coffee
Tue May 16 2023

A quick guide on how to secure a NodeJs express API with Helmet

In this guide we will show how we can secure our NodeJs API using Helmet. Helmet is an open source library that can be downloaded from npmjs. What helmet is doing, is basically adding HTTP response headers. We can also configure each header to suite our needs, and also choose to disable those we don't want.

Example

To use helmet, we can download it using npm

npm i helmet

And then in our API, we use it like this:

const express = require("express"); const helmet = require("helmet"); const PORT = 8089; const app = express(); app.use(helmet()); app.get("/ping", (req, res) => { res.send("pong"); }); app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); });

And that's it. So it basically takes two lines of code to secure our API. And if we want to remove some of the headers, e.g contet-security-policy, it can be done like this:

app.use( helmet({ contentSecurityPolicy: false, }) );

Example of allowing scripts to be loaded through helmet

Or if we want to customize some header, it can be done as well. Example below will allow scripts to be loaded from some trusted sources.

app.use( helmet({ contentSecurityPolicy: { useDefaults: true, directives: { scriptSrc: ["'self'", "some.external.script.we.trust"], }, }, }) );

Outro

That's helmet ladies and gentlemen. I hope you enjoyed this guide. Express apps are insecure by default, since there are no security headers present. That's why tools like helmet is great, since it is super easy to get the security foundation up and running with just a couple of lines of code.

Thanks for reading, and have a great day!

signatureTue May 16 2023
See all our articles