Express router.param() Method

Beginner
⏱️ 9 min read
📚 Updated: May 2026
🎯 3 Code Examples

What you’ll learn

  • How to register parameter middleware with router.param().
  • How to validate params before route handlers run.
  • How to preload records and attach them to req.
  • How to avoid hanging requests and duplicate logic.

Syntax

javascript
router.param(name, function (req, res, next, value) {
  // preprocess value
  next();
});
1

Validate route parameter once

javascript
router.param('userId', function (req, res, next, userId) {
  if (!/^\d+$/.test(userId)) return res.status(400).send('Invalid userId');
  next();
});
2

Preload model by param value

javascript
router.param('postId', function (req, res, next, postId) {
  var post = posts.find(function (p) { return String(p.id) === postId; });
  if (!post) return res.status(404).send('Post not found');
  req.post = post;
  next();
});
3

Use preloaded object in route

javascript
router.get('/posts/:postId', function (req, res) {
  res.json(req.post);
});

⚠️ Common pitfalls

  • Forgetting next() after successful validation/preload.
  • Writing heavy business logic inside router.param() instead of parameter concerns.
  • Assuming it runs for unrelated param names.

❓ FAQ

It registers callback logic for a named route parameter on a router instance.
It runs for matched routes that include the configured parameter name, before route handlers.
Yes. It is commonly used to validate parameter format and return errors early.
Yes. You can fetch records by param value and attach them to req for downstream handlers.
router.param() is scoped to one router module, while app.param() applies at app level.
Did you know?

router.param() runs when a named route parameter is present, making it ideal for validation and preloading records.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

4 people found this page helpful