0
0
Expressframework~5 mins

Application-level middleware in Express

Choose your learning style9 modes available
Introduction

Application-level middleware helps you run code for every request your app gets. It can change requests, responses, or stop the request if needed.

To log every request made to your server for monitoring.
To check if a user is logged in before allowing access to certain pages.
To add headers to all responses for security or tracking.
To parse incoming data like JSON before your routes handle it.
To handle errors or unexpected situations globally.
Syntax
Express
app.use(function (req, res, next) {
  // your code here
  next();
});
Middleware functions take three arguments: req, res, and next.
Always call next() to pass control to the next middleware or route.
Examples
This logs the HTTP method and URL for every request.
Express
app.use((req, res, next) => {
  console.log(`${req.method} ${req.url}`);
  next();
});
This middleware runs only for routes starting with /admin and blocks users who are not admins.
Express
app.use('/admin', (req, res, next) => {
  if (!req.user || !req.user.isAdmin) {
    return res.status(403).send('Access denied');
  }
  next();
});
This built-in middleware parses incoming JSON data so you can use it easily in your routes.
Express
app.use(express.json());
Sample Program

This example shows an application-level middleware that logs every request method and URL. Then it responds with a greeting on the home page.

Express
import express from 'express';

const app = express();

// Application-level middleware to log requests
app.use((req, res, next) => {
  console.log(`Received ${req.method} request for ${req.url}`);
  next();
});

// Simple route
app.get('/', (req, res) => {
  res.send('Hello from Express!');
});

// Start server
app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
OutputSuccess
Important Notes

Middleware order matters: Express runs them in the order you add them.

If you forget to call next(), the request will hang and never reach routes.

You can add middleware for specific paths by passing the path as the first argument to app.use().

Summary

Application-level middleware runs for every request or for specific paths.

It can modify requests, responses, or stop requests early.

Always call next() to continue the request cycle.