Performance: Route matching order matters
This affects server response time and resource usage by determining how quickly the correct route handler is found.
app.get('/about', (req, res) => { res.send('About page'); }); app.get('/:id', (req, res) => { res.send('ID route'); });
app.use((req, res, next) => { next(); });
app.get('/:id', (req, res) => { res.send('ID route'); });
app.get('/about', (req, res) => { res.send('About page'); });| Pattern | Route Checks | Middleware Calls | Response Delay | Verdict |
|---|---|---|---|---|
| General route before specific | Many unnecessary checks | Extra middleware runs | Increased delay | [X] Bad |
| Specific route before general | Minimal checks | Only needed middleware | Faster response | [OK] Good |
app.get('/user', ...) and app.get('/:id', ...) are defined. Which route will handle /user if /:id is defined first?/:id is defined before /user, the path /user matches /:id first, so that handler runs./:id will handle /user. -> Option C/about is handled before any dynamic /:page route in Express?/about must be defined before dynamic routes like /:page to match first./about first, then /:page, ensuring /about matches before dynamic routes.app.get('/product/:id', (req, res) => res.send('Product ' + req.params.id));
app.get('/product/list', (req, res) => res.send('Product List'));/product/list?/product/:id is defined before the specific /product/list route./product/list matches /product/:id first, so it returns 'Product list'.app.get('/:category', handler1);
app.get('/books', handler2);/books always go to handler1. How do you fix this?/:category matches /books first because it is defined before the specific route./books route before the dynamic one ensures /books matches handler2 first.app.get('/books', handler2) before app.get('/:category', handler1). -> Option A/api/users returns a user list/api/:resource returns data for any resource/api/users returns the user list and /api/products returns product data?/api/users must be defined before dynamic routes like /api/:resource to match correctly./api/users first ensures requests to /api/users hit that route, while other resources match the dynamic route./api/users first, then /api/:resource. -> Option DPass the test and this pattern moves unknown