Express IP Filter Middleware

raw JSON →
2.0.2 verified Thu Apr 23 auth: no javascript

express-ip-filter-middleware is an Express.js middleware designed for robust access control, enabling developers to filter incoming requests based on IP addresses or CIDR blocks. It leverages Node.js's built-in `net.BlockList` for efficient management of allowed and denied IP ranges. The current stable version is 2.0.2, with recent releases primarily focusing on dependency updates, indicating an active maintenance cadence. Key differentiators include its explicit `whitelist` and `blacklist` modes, which mimic Apache's `mod_access` behavior, offering precise control over how allow and deny rules interact. It also provides an `ipOverride` option for custom IP address extraction, making it flexible for environments behind proxies or load balancers.

error TypeError: ipFilterMiddleware is not a function
cause Attempting to import `ipFilterMiddleware` as a default export or using CommonJS `require` without property access when it is a named export.
fix
For ESM, use import { ipFilterMiddleware } from 'express-ip-filter-middleware';. For CJS, use const { ipFilterMiddleware } = require('express-ip-filter-middleware');.
error Error: 'mode' is a required option
cause The `mode` property ('whitelist' or 'blacklist') was not provided in the options object passed to `ipFilterMiddleware`.
fix
Add a mode property to your options object, e.g., { mode: 'whitelist', allow, deny }.
error Access denied unexpectedly in whitelist mode
cause Operating in 'whitelist' mode without any IPs or CIDR blocks added to the `allow` list, which by default denies all access.
fix
Ensure that the allow BlockList instance is populated with all desired IP addresses or networks when using mode: 'whitelist'.
breaking The `mode` option ('whitelist' or 'blacklist') is required. Prior versions might have had implicit defaults, but v2.x explicitly enforces this, and omitting it will cause the middleware to throw an error during initialization.
fix Always explicitly define the `mode` option when configuring the `ipFilterMiddleware`.
gotcha In 'whitelist' mode, if both `allow` and `deny` lists are empty, all access will be denied. This behavior is intentional, similar to Apache's `Order Allow,Deny` directive, where an empty `Allow` list defaults to no access.
fix Ensure that your `allow` list contains the necessary IP addresses or CIDR blocks when operating in 'whitelist' mode, or configure `deny` with explicit blocks if you intend to allow everything else.
gotcha If the optional `ipOverride` function is provided and returns an invalid IP address string, the middleware will bail out with an error. This can lead to unexpected server crashes if not handled.
fix Implement robust validation within your `ipOverride` function to ensure it always returns a valid IPv4/IPv6 string or `undefined`. Consider using a `try-catch` block around the middleware in your Express application or a global error handler to gracefully manage such errors.
gotcha While v2.0.0 represents a major version bump, explicit breaking changes from v1.x are not extensively documented in the public changelog. Users migrating from older versions should thoroughly test their applications, as subtle behavioral changes or stricter validations might exist.
fix Review your existing `express-ip-filter-middleware` configurations against the v2 documentation and thoroughly test all IP-filtering scenarios, particularly edge cases involving empty lists, invalid IPs, or proxy setups, when upgrading.
npm install express-ip-filter-middleware
yarn add express-ip-filter-middleware
pnpm add express-ip-filter-middleware

This quickstart initializes an Express app, configures an IP filter in 'whitelist' mode using `node:net.BlockList`, and applies it globally to demonstrate basic access control.

import { BlockList } from 'node:net';
import express from 'express';
import { ipFilterMiddleware } from 'express-ip-filter-middleware';

// Create BlockList instances for allowed and denied IPs
const allow = new BlockList();
allow.addSubnet('192.168.0.0', 16); // Allow entire 192.168.x.x network
allow.addAddress('10.0.0.5'); // Allow a specific IP

const deny = new BlockList();
deny.addAddress('192.168.0.1'); // Deny a specific IP within the allowed subnet

// Configure the middleware options
const options = {
    mode: 'whitelist', // Only explicitly allowed IPs can access
    allow,
    deny,
    // Example of overriding IP detection if behind a proxy
    // ipOverride: (req) => req.headers['x-forwarded-for'] as string || req.ip,
};

// Initialize Express app and apply the IP filter middleware
const app = express();
app.use(ipFilterMiddleware(options));

// Define a protected route
app.get('/', (req, res) => {
    res.send('Welcome, authorized user!');
});

// Start the server
const PORT = 3000;
app.listen(PORT, () => {
    console.log(`Server running on http://localhost:${PORT}`);
});