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:
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
constapp=require('express')();consthelmet=require('helmet');// Using helmet middlewareapp.use(helmet());app.listen(1337);
Help secure Express apps with various HTTP headers
Helmet
Helmet helps secure Express apps by setting HTTP response headers.
Get started
Here's a sample Express app that uses Helmet:
importexpressfrom"express";importhelmetfrom"helmet";constapp=express();// Use Helmet!app.use(helmet());app.get("/",(req,res)=>{res.send("Hello world!");});app.listen(8000);
You can also require("helmet") if you prefer.
By default, Helmet sets the following headers:
Content-Security-Policy: A powerful allow-list of what can happen on your page which mitigates many attacks
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
constapp=require('express')();constxssClean=require('xss-clean');// Protect against XSS attacks, should come before any routesapp.use(xssClean());app.listen(1337);
This library has been deprecated. The implementation is quite simple, and I would suggest you copy the source code directly into your application using the xss-filters dependency, or look for alternative libraries with more features and attention. Thanks for your support.
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.
constrestify=require('restify')constxss=require('xss-clean')constapp=restify.createServer()app.use(restify.bodyParser())// make sure this comes before any routesapp.use(xss())app.listen(8080)
This will sanitize any data in req.body, req.query, and req.params. You can also…
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
constapp=require('express')();consthpp=require('hpp');// Protect against HPP, should come before any routesapp.use(hpp());app.listen(1337);
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
This is a module for node.js and io.js and is installed via npm:
npm install hpp --save
Getting Started
Add the HPP middleware like this:
// ...varhpp=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',
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
constapp=require('express')();constmongoSanitize=require('express-mongo-sanitize');// Remove all keys containing prohibited charactersapp.use(mongoSanitize());app.listen(1337);
Sanitize your express payload to prevent MongoDB operator injection.
Express Mongo Sanitize
Express 4.x middleware which sanitizes user-supplied data to prevent MongoDB Operator Injection.
What is this module for?
This module searches for any keys in objects that begin with a $ sign or contain a ., from req.body, req.query, req.headers or req.params. It can then either:
completely remove these keys and associated data from the object, or
replace the prohibited characters with another allowed character.
The behaviour is governed by the passed option, replaceWith. Set this option to have the sanitizer replace the prohibited characters with the character passed in.
The config option allowDots can be used to allow dots in the user-supplied data. In this case, only instances of $ will be sanitized.
See the spec file for more examples.
Why is it needed?
Object keys starting with a $ or containing a . are reserved for use by MongoDB as operators…
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
constapp=require('express')();constrateLimit=require('express-rate-limit');// Restrict all routes to only 100 requests per IP address every 1o minutesconstlimiter=rateLimit({windowMs:10*60*1000,// 10 minutesmax:100// 100 requests per IP});app.use(limiter);app.listen(1337);
Sponsored by Zuplo a fully-managed API
Gateway for developers. Add
dynamic rate-limiting
authentication and more to any API in minutes. Learn more at
zuplo.com
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.
Alternate Rate Limiters
This module does not share state with other processes/servers by default. If
you need a more robust solution, I recommend using an external store. See the
stores section below for a list of external stores.
This module was designed to only handle the basics and didn't even support
external stores initially. These other options all are excellent pieces of
software and may be more appropriate for some situations:
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.