惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Hugging Face - Blog
Hugging Face - Blog
Microsoft Azure Blog
Microsoft Azure Blog
月光博客
月光博客
S
Securelist
J
Java Code Geeks
Recorded Future
Recorded Future
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
M
MIT News - Artificial intelligence
S
Secure Thoughts
Y
Y Combinator Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
D
Docker
Martin Fowler
Martin Fowler
The Last Watchdog
The Last Watchdog
WordPress大学
WordPress大学
The GitHub Blog
The GitHub Blog
Vercel News
Vercel News
O
OpenAI News
www.infosecurity-magazine.com
www.infosecurity-magazine.com
博客园_首页
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
PCI Perspectives
PCI Perspectives
N
News and Events Feed by Topic
H
Heimdal Security Blog
SecWiki News
SecWiki News
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
博客园 - 【当耐特】
T
Troy Hunt's Blog
L
LINUX DO - 最新话题
Hacker News: Ask HN
Hacker News: Ask HN
Hacker News - Newest:
Hacker News - Newest: "LLM"
N
Netflix TechBlog - Medium
A
Arctic Wolf
The Hacker News
The Hacker News
I
Intezer
S
Schneier on Security
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Apple Machine Learning Research
Apple Machine Learning Research
L
Lohrmann on Cybersecurity
宝玉的分享
宝玉的分享
P
Privacy & Cybersecurity Law Blog
Stack Overflow Blog
Stack Overflow Blog
T
Tor Project blog
小众软件
小众软件
Simon Willison's Weblog
Simon Willison's Weblog
The Cloudflare Blog
Jina AI
Jina AI

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
What is Middleware in Express and How It Works
SATYA SOOTAR · 2026-05-10 · via DEV Community

Hello readers 👋, welcome to the 10th blog in our Node.js series!

In the last post, we built a clean REST API using Express.js for a users resource. We defined routes and handled different HTTP methods. Today, we are going to explore a concept that sits quietly at the heart of every Express application: middleware.

If you have ever wanted to log every request, check authentication tokens, or validate incoming data before it hits your route handler, you have needed middleware. Let's understand what middleware is, how it fits into the request lifecycle, the different types, and how to chain multiple middleware to build powerful, reusable pipelines.

Let's get started.

What middleware is in Express

Middleware, in Express, are functions that have access to the request object (req), the response object (res), and the next middleware function in the application's request-response cycle. The next middleware function is conventionally denoted by a variable named next.

Think of middleware as a series of checkpoints or processing stations that every incoming request passes through before reaching the final route handler. At each checkpoint, you can:

  • Inspect or modify the request (e.g., add properties, parse the body).
  • Perform some logic (e.g., log the request time, check authentication).
  • Send an early response (e.g., return an error if the user is not authenticated) and stop the chain.
  • Call next() to pass control to the next middleware in line.

Middleware functions are executed in the order they are defined. That order is crucial and we'll explore it soon.

Where middleware sits in the request lifecycle

In a typical Express app, an incoming HTTP request flows through a pipeline:

  1. The request arrives at the server.
  2. It passes through each middleware function registered (both application-level and router-level) in the order they were added.
  3. Finally, it reaches the route handler that matches the path and method.
  4. The route handler sends a response.
  5. If no middleware or route sends a response, the request hangs; Express doesn't automatically respond.

The middleware chain can be visualized as:

Request → [Middleware 1] → [Middleware 2] → [Route Handler] → Response

Enter fullscreen mode Exit fullscreen mode

Each arrow is a next() call. If a middleware function does not call next(), the request stalls and never reaches the next middleware or route handler (unless you send a response and end the request). This pipeline concept is the backbone of Express.

The role of next()

The next function is a callback that tells Express "I'm done, move on to the next middleware or route handler." If the currently executing middleware function does not end the request-response cycle, it must call next().

There are two important variations:

  • next() – proceed to the next middleware in the stack.
  • next('route') – skip to the next route handler (only works in router-level middleware).

If you pass an error to next(err), Express skips all remaining non-error middleware and goes directly to an error-handling middleware, which has four parameters: (err, req, res, next). We'll keep error handling middleware for another post.

Application-level middleware

Application-level middleware are bound to an instance of the app object using app.use() or app.METHOD(). They run for every request (if no path is specified) or for requests that match a specific path prefix.

Example: logging middleware for every request

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

// Application-level middleware (no path, runs on every request)
app.use((req, res, next) => {
  console.log(`${req.method} ${req.url} - ${new Date().toISOString()}`);
  next();
});

Enter fullscreen mode Exit fullscreen mode

Here, we log the HTTP method, URL, and timestamp for every request. We then call next() so the request continues down the pipeline.

Example: middleware for a specific path

You can limit middleware to a path prefix:

app.use('/admin', (req, res, next) => {
  console.log('Admin route accessed');
  next();
});

Enter fullscreen mode Exit fullscreen mode

Middleware added this way will run for any route starting with /admin.

Router-level middleware

Router-level middleware works exactly like application-level middleware, except it is bound to an instance of express.Router(). It's used to organize route-specific middleware, especially when you have modular route files.

const router = express.Router();

// Router-level middleware: runs for every request handled by this router
router.use((req, res, next) => {
  console.log('Inside user router');
  next();
});

router.get('/profile', (req, res) => {
  res.send('User profile');
});

app.use('/users', router);

Enter fullscreen mode Exit fullscreen mode

Now, any request starting with /users will first go through the router-level middleware before hitting the specific route handler.

Built-in middleware

Express has some built-in middleware functions that solve common tasks. You've already seen one: express.json(). These are middleware functions that come with Express and are used via app.use().

  • express.json() – parses incoming JSON payloads and populates req.body.
  • express.urlencoded({ extended: true }) – parses URL-encoded payloads (from HTML forms).
  • express.static('public') – serves static files (images, CSS, JS) from a directory.

Example:

app.use(express.json());
app.use(express.static('public'));

Enter fullscreen mode Exit fullscreen mode

These are middleware too! They process the request and call next() for the next piece in the pipeline.

Execution order of middleware

The order in which you declare middleware matters immensely. Express executes them sequentially, top to bottom. If you place a middleware that sends a response before your route handler, the route handler will never run.

Consider this incorrect example:

app.use((req, res, next) => {
  res.send('This ends the request');
  next(); // This will still be called but no further middleware can modify the response after send
});
app.get('/', (req, res) => {
  res.send('Hello world');
});

Enter fullscreen mode Exit fullscreen mode

Here, the first middleware sends a response, and unless you call next() before send(), the get handler never sees the request. More importantly, even if you call next() after send(), Express will not allow you to send another response; you'd get an error because headers are already sent. So, typically you either call next() without sending a response, or you end the request inside the middleware.

The correct pattern:

app.use((req, res, next) => {
  console.log('Logging');
  next(); // pass control
});

app.use((req, res, next) => {
  // maybe add timestamp to req
  req.requestTime = Date.now();
  next();
});

app.get('/', (req, res) => {
  res.send(`Hello world, request at ${req.requestTime}`);
});

Enter fullscreen mode Exit fullscreen mode

Each middleware adds something and passes control. The route handler runs at the end.

Real-world examples

Let's see three practical middleware: logging, authentication, and request validation.

Logging middleware

You've already seen a basic logger. Let's write a slightly cleaner one:

function logger(req, res, next) {
  const start = Date.now();
  res.on('finish', () => {
    const duration = Date.now() - start;
    console.log(`${req.method} ${req.originalUrl} ${res.statusCode} - ${duration}ms`);
  });
  next();
}
app.use(logger);

Enter fullscreen mode Exit fullscreen mode

This logs the method, URL, status code, and response time. It uses the finish event on the response to know when the response is sent.

Authentication middleware

This one checks for a valid JWT token (similar to our earlier JWT blog). If invalid, it stops the request with a 401 error. Otherwise, it attaches the user and continues.

function authenticate(req, res, next) {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];
  if (!token) {
    return res.status(401).json({ message: 'Access token missing' });
  }
  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    req.user = decoded;
    next();
  } catch (err) {
    return res.status(403).json({ message: 'Invalid token' });
  }
}
// Protect a route
app.get('/profile', authenticate, (req, res) => {
  res.send(`User profile for ${req.user.userId}`);
});

Enter fullscreen mode Exit fullscreen mode

Notice how the middleware stops the request (by returning a response) when authentication fails, so the route handler never executes.

Request validation middleware

You can validate input before it reaches business logic. This keeps your route handlers clean. Here's a simple one for creating a user:

function validateUserInput(req, res, next) {
  const { name, email } = req.body;
  if (!name || !email) {
    return res.status(400).json({ message: 'Name and email are required' });
  }
  if (typeof email !== 'string' || !email.includes('@')) {
    return res.status(400).json({ message: 'Invalid email' });
  }
  next();
}

app.post('/users', validateUserInput, (req, res) => {
  // create user logic...
});

Enter fullscreen mode Exit fullscreen mode

When validation fails, we respond immediately with 400 Bad Request. Otherwise, next() passes control to the actual handler. This separation improves readability and reusability.

Middleware pipeline

Imagine a physical pipeline with several inspection stations. A request arrives, gets stamped at the logging station, then passes through a security gate (authentication), then a quality check (validation), and finally reaches the desired destination (route handler). At any point, if it fails inspection, it gets turned away with a response.

Middleware pipeline

Conclusion

Middleware is one of those concepts that, once you understand it, Express becomes transparent. It's just a sequence of functions that have access to req and res and can either pass the request along with next() or end the cycle by sending a response. By chaining middleware, you can separate concerns like logging, authentication, and validation, making your code cleaner and more maintainable.

Let's quickly recap:

  • Middleware functions sit between the incoming request and the final route handler.
  • They can modify the request/response, run code, or end the request early.
  • The next() function passes control to the next middleware in the stack; without it, the request stalls.
  • Application-level middleware (app.use()) runs for all requests or a specific path.
  • Router-level middleware (router.use()) works for a specific router.
  • Built-in middleware like express.json() are just prepackaged middleware.
  • Execution order is top-to-bottom, so declare middleware before routes they should affect.
  • Real-world uses include logging, authentication, and input validation, which keep route handlers focused.

Now that you understand middleware, you can structure Express apps that are modular, secure, and easy to scale. In the next post, we'll continue building more practical features. See you there!


Hope you found this helpful! If you spot any mistakes or have suggestions, let me know. You can find me on LinkedIn and X, where I post more about web development.