DEV Community

loading...
Cover image for 5 NPM Packages to Secure Your Node.js Backend in 5 Minutes

5 NPM Packages to Secure Your Node.js Backend in 5 Minutes

itsnitinr profile image Nitin Ranganath ・3 min read

When you start to focus on the performance and security of your backend alongside the other features, you know that you're growing and maturing as a developer. It goes without saying but having some sort of security measure against common attacks is essential, even if it's just a hobby project.

If you're new to security or want to quickly get started with some basic protection, these 5 NPM packages will help you get started in just a few minutes. The best part about these packages is that all you have to do is just install them and use them as middleware. It's that easy!

In a hurry or just need the list of packages? Here are the 5 NPM packages that I'll be going over:

Package Name Package Link
helmet NPM Link
xss-clean NPM Link
hpp NPM Link
express-mongo-sanitize NPM Link
express-rate-limit NPM Link

Helmet

What it does: Sets security-related HTTP response headers to protect against some well-known web vulnerabilities.

What does it protect against: Cross-site scripting attacks, cross-site injections, clickjacking, MIME sniffing and targeted attacks towards Express servers by disabling the X-Powered-By header.

How to use it:

npm install helmet
Enter fullscreen mode Exit fullscreen mode
const app = require('express')();
const helmet = require('helmet');

// Using helmet middleware
app.use(helmet());

app.listen(1337);
Enter fullscreen mode Exit fullscreen mode

GitHub logo helmetjs / helmet

Help secure Express apps with various HTTP headers

Helmet

npm version npm dependency status FOSSA Status

Helmet helps you secure your Express apps by setting various HTTP headers. It's not a silver bullet, but it can help!

Quick start

First, run npm install helmet --save for your app. Then, in an Express app:

const express = require("express");
const helmet = require("helmet");

const app = express();

app.use(helmet());

// ...
Enter fullscreen mode Exit fullscreen mode

How it works

Helmet is Connect-style middleware, which is compatible with frameworks like Express. (If you need support for other frameworks or languages, see this list.)

The top-level helmet function is a wrapper around 15 smaller middlewares, 11 of which are enabled by default.

In other words, these two things are equivalent:

// This...
app.use(helmet());
// ...is equivalent to this:
app.use(helmet.
Enter fullscreen mode Exit fullscreen mode

XSS-Clean

What it does: Sanitizes user input coming from POST request body (req.body), GET request query (req.query) and URL parameters (req.params).

What does it protect against: Cross-site scripting / XSS attacks.

How to use it:

npm install xss-clean
Enter fullscreen mode Exit fullscreen mode
const app = require('express')();
const xssClean = require('xss-clean');

// Protect against XSS attacks, should come before any routes
app.use(xssClean());

app.listen(1337);
Enter fullscreen mode Exit fullscreen mode

GitHub logo jsonmaur / xss-clean

Middleware to sanitize user input

Node.js XSS-Clean

Build Status Coverage Status

Node.js Connect middleware to sanitize user input coming from POST body, GET queries, and url params. Works with Express, Restify, or any other Connect app.

How to Use

npm install xss-clean --save
Enter fullscreen mode Exit fullscreen mode
var restify = require('restify')
var xss = require('xss-clean')

var app = restify.createServer()

app.use(restify.bodyParser())

/* make sure this comes before any routes */
app.use(xss())

app.listen(8080)
Enter fullscreen mode Exit fullscreen mode

This will sanitize any data in req.body, req.query, and req.params. You can also access the API directly if you don't want to use as middleware.

var clean = require('xss-clean/lib/xss').clean

var cleaned = clean('<script></script>')
// will return "&lt;script>&lt;/script>"
Enter fullscreen mode Exit fullscreen mode

License

MIT © Jason Maurer

HPP

What it does: Puts the array parameters in req.query and/or req.body asides and just selects the last parameter value to avoid HTTP Parameter Pollution attacks.

What does it protect against: Bypassing input validations and denial of service (DoS) attacks by uncaught TypeError in async code, leading to server crash.

How to use it:

npm install hpp
Enter fullscreen mode Exit fullscreen mode
const app = require('express')();
const hpp = require('hpp');

// Protect against HPP, should come before any routes
app.use(hpp());

app.listen(1337);
Enter fullscreen mode Exit fullscreen mode

GitHub logo analog-nico / hpp

Express middleware to protect against HTTP Parameter Pollution attacks

HPP

Express middleware to protect against HTTP Parameter Pollution attacks

Build Status Coverage Status Dependency Status

Why?

Let Chetan Karande's slides do the explaining:

Slide 48 Slide 49 Slide 50 Slide 54

...and exploits may allow bypassing the input validation or even result in denial of service.

And HPP solves this how exactly?

HPP puts array parameters in req.query and/or req.body aside and just selects the last parameter value. You add the middleware and you are done.

Installation

NPM Stats

This is a module for node.js and io.js and is installed via npm:

npm install hpp --save
Enter fullscreen mode Exit fullscreen mode

Getting Started

Add the HPP middleware like this:

// ...
var hpp = require('hpp');
// ...
app.use(bodyParser.urlencoded()); // Make sure the body is parsed beforehand.

app.use(hpp()); // <- THIS IS THE NEW LINE

// Add your own middlewares afterwards, e.g.:
app.get('/search',
Enter fullscreen mode Exit fullscreen mode

Express Mongo Sanitize

What it does: Searches for any keys in objects that begin with a $ sign or contain a . from req.body, req.query or req.params and either removes such keys and data or replaces the prohibited characters with another allowed character.

What does it protect against: MongoDB Operator Injection. Malicious users could send an object containing a $ operator, or including a ., which could change the context of a database operation.

How to use it:

npm install express-mongo-sanitize
Enter fullscreen mode Exit fullscreen mode
const app = require('express')();
const mongoSanitize = require('express-mongo-sanitize');

// Remove all keys containing prohibited characters
app.use(mongoSanitize());

app.listen(1337);
Enter fullscreen mode Exit fullscreen mode

GitHub logo fiznool / express-mongo-sanitize

Sanitize your express payload to prevent MongoDB operator injection.

Express Mongoose Sanitize

Express 4.x middleware which sanitizes user-supplied data to prevent MongoDB Operator Injection.

Build Status npm version npm downloads per week Dependency Status devDependency Status

Installation

npm install express-mongo-sanitize
Enter fullscreen mode Exit fullscreen mode

Usage

Add as a piece of express middleware, before defining your routes.

const express = require('express');
const bodyParser = require('body-parser');
const mongoSanitize = require('express-mongo-sanitize');

const app = express();

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

// To remove data, use:
app.use(mongoSanitize());

// Or, to replace prohibited characters with _, use:
app.use(
  mongoSanitize({
    replaceWith: '_',
  }),
);
Enter fullscreen mode Exit fullscreen mode

onSanitize

onSanitize callback is called after the request's value was sanitized.

app.use(
  mongoSanitize({
    onSanitize: ({
Enter fullscreen mode Exit fullscreen mode

Express Rate Limit

What does it do: Used to limit IP addresses from making repeated requests to API endpoints. An example would be to rate limit an endpoint that is responsible for sending password reset emails, which can incur additional fees.

What does it protect against: Brute force, denial of service (DoS) and distributed denial of service (DDoS) attacks.

How to use it:

npm install express-rate-limit
Enter fullscreen mode Exit fullscreen mode
const app = require('express')();
const rateLimit = require('express-rate-limit');

// Restrict all routes to only 100 requests per IP address every 1o minutes
const limiter = rateLimit({
    windowMs: 10 * 60 * 1000,    // 10 minutes
    max: 100                     // 100 requests per IP
});
app.use(limiter);

app.listen(1337);
Enter fullscreen mode Exit fullscreen mode

GitHub logo nfriedly / express-rate-limit

Basic rate-limiting middleware for express

Express Rate Limit

Node.js CI NPM version npm downloads

Basic rate-limiting middleware for Express. Use to limit repeated requests to public APIs and/or endpoints such as password reset.

Plays nice with express-slow-down.

Note: this module does not share state with other processes/servers by default. It also buckets all requests to an internal clock rather than starting a new timer for each end-user. It's fine for abuse-prevention but might not produce the desired effect when attempting to strictly enforce API rate-limits or similar. If you need a more robust solution, I recommend using an external store:

Stores

  • Memory Store (default, built-in) - stores hits in-memory in the Node.js process. Does not share state with other servers or processes, and does not start a separate timer for each end user.
  • Redis Store
  • Memcached Store
  • Mongo Store

Alternate Rate-limiters

This module was designed to only handle the basics and didn't even support external stores initially. These other options…


With these 5 NPM packages, you can make your Node.js + Express.js application much more secure in just 5 minutes. All of the packages above are extremely easy to use, just export and use as a middleware.

What security precautions do you take? Or did I miss any of your favorite packages? Let me know in the discussion below and I'll be happy to hear your thoughts.

Discussion (5)

Collapse
geobrodas profile image
Georgey

I'm a Web developer, and I recently took up a ethical hacking course to see how I can combine the knowledge to my expertise in web dev. And one thing which actually worried me was the Man in the middle attack. Good to see there is a way to prevent this. Thanks a ton for sharing this!!! Great job!

Collapse
itsnitinr profile image
Nitin Ranganath Author

Oh wow, I'm really glad you found the article to be helpful. Could you link me to the course you're talking about, curious about the content. Thanks for reading!

Collapse
geobrodas profile image
Georgey

Sure actually it's an internship course I'm doing, which I got after answering the exam NEO. It happens once in a year.

Collapse
ridaehamdani profile image
Ridae HAMDANI

I am using mongo as database for a while and I was worried about malicious data which can change my initial query , I think mongo sanitize will help me ... Thanks @itsnitinr for you article

Collapse
itsnitinr profile image
Nitin Ranganath Author

I'm sure it will. Glad to have helped you out and thank you for reading.

Forem Open with the Forem app