Beginner LevelExpress JS
How do you constrain Express route parameters using regular expressions?
❓ Interview Prompt: Explain Express route parameter regex constraints (:id(\d+)) and dropping invalid route paths automatically.
By default, route parameters like '/users/:id' match any string value (e.g. '/users/42' or '/users/abc-xyz').
Constraining Parameters via Regex:
You can append a regular expression in parentheses directly after the parameter name in the route definition:
'app.get("/users/:id(\\d+)", ...)'.
•
If the incoming parameter matches the regex (digits only), the route handler executes.
•
If it fails the regex match, Express skips the route and continues down the middleware stack to check subsequent routes or 404 handlers.
Code Implementation Example
javascript
import express from 'express';
const app = express();
// Matches ONLY numeric IDs (e.g., /users/42)
app.get('/users/:id(\d+)', (req, res) => {
res.json({ type: 'numeric', id: req.params.id });
});
// Matches alphanumeric user handles (e.g., /users/alice_dev)
app.get('/users/:username([a-zA-Z0-9_]+)', (req, res) => {
res.json({ type: 'username', username: req.params.username });
});💡Constraining route parameters using inline regular expressions.
🎯 Interview Key Takeaway
Append regex constraints in parentheses after parameter names (:id(\d+)) to validate route parameters at the routing layer.
#Routing#Regex#req.params#Beginner
Back to all Express JS Questions→