Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

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-* headersapp.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 dataapp.use(mongoSanitize());//Set security headersapp.use(helmet());//Prevent XSS attacksapp.use(xss());//Prevent http param pollutionapp.use(hpp());//CORSconst 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 modeExit fullscreen mode

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Talks about Tech (both Technical and Leadership), views are my own2 x AWS Certified | 4 x MongoDB Certified | DevSecOps Leader and Professional
  • Location
    Singapore
  • Work
    Senior Consulting Engineer @ MongoDB
  • Joined

More fromHejun Wong

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp