Logo

dev-resources.site

for different kinds of informations.

NodeJS Security Middlewares

Published at
6/11/2024
Categories
security
middleware
api
node
Author
herjean7
Categories
4 categories in total
security
open
middleware
open
api
open
node
open
Author
8 person written this
herjean7
open
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
middleware Article's
30 articles in total
Favicon
I Really like Middleware in NodeJs/Express.
Favicon
CSRF tokens in Nextjs
Favicon
Create Your Own Middleware Application Using Chain of Responsibility
Favicon
Rust: Demystifying Middleware in Actix Web
Favicon
Apache Camel - The Integration Framework for Modern Applications
Favicon
Express.js Applications with Middleware
Favicon
Nostr: a Better Future for Authentication
Favicon
Building Secure, Scalable, and Low-Latency IoT Middleware
Favicon
How to Build Scalable Middleware with Express.js
Favicon
How to quickly add API Key validation to a Node Express API
Favicon
Middleware in Lithe: How It Works and How to Create Your Own
Favicon
Middleware no Lithe: Como Funciona e Como Criar o Seu PrΓ³prio
Favicon
πŸ—ΊοΈ Peta Jalan Laravel: Menjelajah Routing, Middleware, dan Controller (Indonesian Version)
Favicon
Centralized Exception Handling in ASP.NET Core - Custom Middleware
Favicon
Adding Logging and Error Handling Middleware to Your Go API
Favicon
A Simple Way to Handle Locale-Specific URLs in Express
Favicon
Entendendo e Implementando Middlewares no Express.js
Favicon
Deep Dive ASP.NET Core Middleware : Part 1
Favicon
Next.js Middleware: Simple Guide to Control Requests
Favicon
Building a middleware with Nextjs
Favicon
Extending Prisma ORM with Custom Middleware: Logging, Validation, and Security
Favicon
Understanding NestJS Middleware
Favicon
Implementing Secure Authentication in Next.js with JWT and MongoDB. Protect Routes using middleware
Favicon
Middleware function Execution Problem and Solution
Favicon
Securing Next.js APIs with Middleware Using Environment Variables
Favicon
Middleware and Interceptors in NestJS: Best Practices
Favicon
NodeJS Security Middlewares
Favicon
Middleware to Asp.net Core MVC Application + Custom Middleware
Favicon
Implementing CORS in a Custom Next.js Server
Favicon
How to Set Up Signup, Login, and Logout using Django's Middleware

Featured ones: