Age Check & IP Address Middleware with Code Examples

Create Server

import express from "express";

const app = express();

app.get("/", (req, resp) => {
resp.send("<h1>Home Page</h1>");
});

app.get("/login", (req, resp) => {
resp.send("<h1>Login Page</h1>");
});

app.get("/admin", (req, resp) => {
resp.send("<h1>Admin Page</h1>");
});

app.listen(3200);


Middleware for Age Check

Function Purpose:

  1. Checks if user provided age in the query (?age=20)
  2. Blocks access if age is missing or less than 18


Code:

function ageCheck(req, resp, next) {
if (!req.query.age || req.query.age < 18) {
resp.send("Alert ! You can not access this page");
} else {
next();
}
}

app.use(ageCheck); // Applies globally to all routes


Middleware for IP Check

Function Purpose:

  1. Logs the visitor's IP address
  2. Blocks access for specific IP (example: 192.168.1.23)
function ipCheck(req, resp, next) {
const ip = req.socket.remoteAddress;
console.log(ip); // View in terminal

if (ip.includes("192.168.1.23")) {
resp.send("Alert ! You can not access this page");
} else {
next();
}
}

app.use(ipCheck); // Applies globally


How to Find Your IP Address

Windows Command Prompt:

ipconfig


Mac Terminal:

ipconfig getifaddr en0