Intermediate LevelExpress JS
How does router.param() intercept and pre-load database resources whenever a specific parameter appears?
❓ Interview Prompt: Explain router.param() middleware, URL parameter preloading, avoiding duplicated database lookup logic, and error handling.
'router.param(name, callback)' registers parameter-interception middleware that executes automatically whenever a URL parameter (like ':userId') appears in a matching route.
Pre-Loading Data:
Instead of querying the database for a user in 10 different route handlers, 'router.param("userId", ...)' fetches the user once, attaches it to 'req.user', and passes control to the route handler!
Code Implementation Example
javascript
import express from 'express';
const router = express.Router();
// Executed automatically whenever :userId appears in any route URL!
router.param('userId', async (req, res, next, id) => {
try {
const user = await db.findUser(id);
if (!user) return res.status(404).json({ error: 'User not found' });
req.user = user; // Pre-load user object!
next();
} catch (err) {
next(err);
}
});
router.get('/users/:userId', (req, res) => res.json(req.user));
router.delete('/users/:userId', (req, res) => res.json({ deleted: req.user }));💡Pre-loading database resources automatically using router.param().
🎯 Interview Key Takeaway
Use router.param() to intercept URL parameters and pre-load database resources before route controllers execute.
#router.param#Middleware#Routing#Intermediate
Back to all Express JS Questions→