0
0
Expressframework~5 mins

Route matching order matters in Express

Choose your learning style9 modes available
Introduction

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.

When you have multiple routes that could match similar URLs.
When you want a specific route to handle requests before a more general route.
When you use wildcard or parameter routes that can catch many URLs.
When you want to avoid unexpected route handling by placing specific routes first.
When debugging why a route is not being reached because another route matched first.
Syntax
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.

Examples
Specific route '/users/all' is placed before the parameter route '/users/:id' to avoid matching 'all' as an id.
Express
app.get('/users/all', (req, res) => {
  res.send('All users')
})

app.get('/users/:id', (req, res) => {
  res.send(`User ${req.params.id}`)
})
Wildcard route placed before specific route causes the specific route never to run.
Express
app.get('/files/*', (req, res) => {
  res.send('Wildcard route')
})

app.get('/files/special', (req, res) => {
  res.send('Special file')
})
Correct order: specific route first, wildcard last.
Express
app.get('/files/special', (req, res) => {
  res.send('Special file')
})

app.get('/files/*', (req, res) => {
  res.send('Wildcard route')
})
Sample Program

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.

Express
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')
})
OutputSuccess
Important Notes

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.

Summary

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.