0
0
Expressframework~5 mins

Router level middleware in Express

Choose your learning style9 modes available
Introduction

Router-level middleware helps organize code by running functions only for specific groups of routes. It keeps your app tidy and easier to manage.

You want to apply a check or setup only to routes under a certain path, like '/users'.
You need to add logging or authentication only for a part of your app.
You want to reuse middleware for multiple routes grouped together.
You want to keep your main app file clean by separating route logic.
You want to handle errors or modify requests for a specific router.
Syntax
Express
const router = express.Router();

router.use((req, res, next) => {
  // middleware code here
  next();
});

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

Router-level middleware is attached to an instance of express.Router().

Use router.use() to add middleware that runs for all routes in that router.

Examples
This middleware logs a message every time a route in this router is accessed.
Express
const router = express.Router();

// Middleware for all routes in this router
router.use((req, res, next) => {
  console.log('Router middleware running');
  next();
});
A simple route inside the router that sends a greeting.
Express
router.get('/hello', (req, res) => {
  res.send('Hello from router!');
});
This mounts the router on the '/users' path, so all router routes start with '/users'.
Express
app.use('/users', router);
Sample Program

This example creates a router with middleware that logs a message for all '/users' routes. It has two routes: '/' and '/profile'. The router is mounted on '/users', so the full paths are '/users/' and '/users/profile'.

Express
import express from 'express';

const app = express();
const router = express.Router();

// Router-level middleware
router.use((req, res, next) => {
  console.log('Middleware for /users routes');
  next();
});

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

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

// Mount router on /users path
app.use('/users', router);

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

Always call next() in middleware to pass control to the next handler.

Router-level middleware only affects routes defined on that router.

You can add multiple middleware functions to a router for layered processing.

Summary

Router-level middleware runs only for routes in a specific router.

It helps organize and reuse middleware for grouped routes.

Use router.use() to add middleware to a router.