Route matching order matters because Express checks routes in the order you write them. The first route that matches the request is used, so order controls which code runs.
Route matching order matters in Express
app.METHOD(PATH, HANDLER) // Example: app.get('/users/all', handlerFunction) app.get('/users/:id', handlerFunction)
Routes are checked top to bottom in the order they appear in your code.
More specific routes should come before more general or wildcard routes.
app.get('/users/all', (req, res) => { res.send('All users') }) app.get('/users/:id', (req, res) => { res.send(`User ${req.params.id}`) })
app.get('/files/*', (req, res) => { res.send('Wildcard route') }) app.get('/files/special', (req, res) => { res.send('Special file') })
app.get('/files/special', (req, res) => { res.send('Special file') }) app.get('/files/*', (req, res) => { res.send('Wildcard route') })
This example shows the specific route before the parameter route. Requests to '/item/special' will match the specific route first and not the parameter route.
Placing the specific route first ensures correct matching.
import express from 'express' const app = express() app.get('/item/special', (req, res) => { res.send('Special Item') }) app.get('/item/:id', (req, res) => { res.send(`Item ID: ${req.params.id}`) }) app.listen(3000, () => { console.log('Server running on http://localhost:3000') })
Always put specific routes before parameter or wildcard routes to ensure correct matching.
Order affects which route handles the request, so plan route order carefully.
Use console logs or debugging to check which route runs if unsure.
Express matches routes in the order they are defined.
Specific routes should come before general or wildcard routes.
Route order controls which handler runs for a request.