DEV Community

Hejun Wong
Hejun Wong

Posted on

NodeJS Security Middlewares

Introduction

Many backend endpoints are written in NodeJS and it is crucial for us to protect our endpoints. A quick and simple way to do so would be to use middlewares.

Middleware

Middlewares allow us intercept and inspect requests, which makes it ideal for logging, authentication and inspecting requests. Here are 6 security middlewares which you can embed into your NodeJS project to secure it.

Helmet

The Helmet package sets security headers in our API responses. These headers provide important security-related instructions to the browser or client about how to handle the content and communication, thus helping to prevent various types of attacks.

CORS

The CORS package allows us to whitelist domains, controlling access to our web resources.

Express XSS Sanitizer

This package sanitizes user input data to prevent Cross Site Scripting (XSS) attacks

Express Rate Limit

If your Backend Servers are not fronted with a Web Application Firewall (WAF) or protected by DDoS mitigation services, you should definitely install this package to protect your endpoints from getting spammed by setting rate limits.

Express Mongo Sanitizer

This package sanitizes user-supplied data to prevent MongoDB Operator Injection.

HPP

As Express populates HTTP request parameters with the same name into an array, attackers may pollute the HTTP parameters to exploit this mechanism.

Sample Code on Usage

const express = require('express');
const app = express();

const cors = require("cors");
const helmet = require("helmet");
const { xss } = require("express-xss-sanitizer");
const rateLimit = require("express-rate-limit");
const hpp = require("hpp");
const mongoSanitize = require("express-mongo-sanitize");


// Rate limit 

// Trust the X-Forwarded-* headers
app.set("trust proxy", 2);

const IP_WHITELIST = (process.env.IP_WHITELIST || "").split(",");

const limiter = rateLimit({
  windowMs: 10 * 60 * 1000, // 10 mins
  max: 500, // Limit each IP to 500 requests per 10 mins
  standardHeaders: true, //Return rate limit info in the `RateLimit-*` headers
  legacyHeaders: false, // Disable the 'X-RateLimit-*' headers
  skip: (request, response) => IP_WHITELIST.includes(request.ip),
});

app.use(limiter);

//Sanitize data
app.use(mongoSanitize());

//Set security headers
app.use(helmet());

//Prevent XSS attacks
app.use(xss());

//Prevent http param pollution
app.use(hpp());

//CORS

const whitelist = ['http://localhost:4000']; 

const corsOptions = {
  origin: function (origin, callback) {
    if (whitelist.indexOf(origin) !== -1) {
      callback(null, true)
    } else {
      callback(new Error('Not allowed by CORS'))
    }
  }
}

app.use(cors(corsOptions));

Enter fullscreen mode Exit fullscreen mode

Top comments (0)