Routing in Express

By

Published · Updated

Tagged: Express.js

How routing works in Express 5: route methods, named parameters, wildcards, optional segments, regular expressions, app.route(), express.Router(), route order and 404 pages.

Routing is the process of determining what should happen when a URL is called, or also which parts of the application should handle a specific incoming request.

In the Hello World example we used this code

app.get('/', (req, res) => { /* */ })

This creates a route that maps accessing the root domain URL / using the HTTP GET method to the response we want to provide.

The examples in this post use Express 5, the current major version, which needs Node.js 18 or higher. Express 5 changed the path syntax, so if you’re coming from Express 4, check the last section of this post.

Route methods

There’s a method for each HTTP verb: app.get(), app.post(), app.put(), app.delete(), app.patch() and so on.

app.get('/books', (req, res) => res.send('List books'))
app.post('/books', (req, res) => res.send('Add a book'))
app.delete('/books/:id', (req, res) => res.send('Delete a book'))

app.all() matches a path for every HTTP method. It’s handy to run some code first and then pass control on with next():

app.all('/admin', (req, res, next) => {
  console.log('Someone called /admin')
  next()
})

Every route must end the request, with res.send(), res.json(), res.redirect(), res.sendFile(), res.sendStatus(), res.render(), res.download(), res.end() or res.jsonp(). If you call none of them, the request is left hanging and the browser keeps waiting.

Named parameters

What if we want to listen for custom requests, maybe we want to create a service that accepts a string, and returns that uppercase, and we don’t want the parameter to be sent as a query string, but part of the URL. We use named parameters:

app.get('/uppercase/:theValue', (req, res) => res.send(req.params.theValue.toUpperCase()))

If we send a request to /uppercase/test, we’ll get TEST in the body of the response.

You can use multiple named parameters in the same URL, and they will all be stored in req.params:

app.get('/users/:userId/books/:bookId', (req, res) => res.json(req.params))

/users/34/books/8989 returns {"userId":"34","bookId":"8989"}.

Values in req.params are always strings. If you need a number, convert it with Number(req.params.userId) and check the result.

The hyphen and the dot are read literally, so you can use them to split one segment into two parameters:

app.get('/flights/:from-:to', (req, res) => res.json(req.params))

/flights/LAX-SFO gives you {"from":"LAX","to":"SFO"}.

A parameter name must be a valid JavaScript identifier, like userId or post_id. For other names, quote them: /:"user-name".

Don’t confuse route parameters with the query string. In /search?q=express&page=2 the path is just /search, and the rest ends up in req.query:

app.get('/search', (req, res) => res.json(req.query))
// /search?q=express&page=2 -> {"q":"express","page":"2"}

The query string never takes part in route matching. I explain req.query in detail in how to retrieve the GET query string parameters.

Optional segments

Wrap a part of the path in braces to make it optional:

app.get('/docs{/:page}', (req, res) => {
  res.send(req.params.page ?? 'index')
})

This matches both /docs (prints index) and /docs/routing (prints routing). When the optional parameter is missing, it’s not in req.params at all, so check for undefined.

Wildcards

A wildcard matches one or more path segments. In Express 5 it must have a name:

app.get('/files/*filepath', (req, res) => res.json(req.params))

/files/images/logo.png returns {"filepath":["images","logo.png"]}. Notice the value is an array of segments, not a string. Use req.params.filepath.join('/') to get images/logo.png back.

/files alone doesn’t match, because the wildcard needs at least one segment. To also match the base path, wrap it in braces. This is the common catch-all route:

app.get('/{*splat}', (req, res) => {
  res.send('This matches every path, including /')
})

Use a regular expression to match a path

You can use regular expressions to match multiple paths with one statement:

app.get(/post/, (req, res) => { /* */ })

will match /post, /post/first, /thepost, /posting/something, and so on.

That’s very broad. When I tested it, it also caught /posts/7/comments, a route I meant to handle with a router further down. Anchor the expression with ^ and $ to match only what you want. Capture groups end up in req.params with numeric keys:

app.get(/^\/archive\/(\d{4})$/, (req, res) => {
  res.send(`Posts from ${req.params[0]}`)
})

/archive/2024 matches and req.params[0] is '2024'. /archive/abc doesn’t match.

Regular expressions work when you pass a RegExp object like above. Inside a string path they don’t: '/user/:id(\\d+)' throws an error in Express 5. Validate the parameter inside the handler instead, or pass an array of paths if you want one handler for a few routes:

app.get(['/discussion/:slug', '/page/:slug'], (req, res) => {
  res.send(req.params.slug)
})

Route order matters

Express checks routes in the order you define them, and the first one that sends a response wins:

app.get('/about', (req, res) => res.send('About'))
app.get('/about', (req, res) => res.send('never reached'))

So put specific routes before generic ones. A catch-all like /{*splat} or a broad regex placed at the top will swallow the routes below it.

By default matching is not case sensitive and ignores a trailing slash: /about, /About and /about/ all hit the same route.

Multiple handlers and next(‘route’)

A route can have more than one handler. Each one calls next() to pass control to the following one. This is how you add middleware to a single route:

const requireLogin = (req, res, next) => {
  if (!req.headers.authorization) return res.status(401).send('Login first')
  next()
}

app.get('/dashboard', requireLogin, (req, res) => res.send('Dashboard'))

Calling next('route') skips the remaining handlers of the current route and jumps to the next route that matches:

app.get('/user/:id', (req, res, next) => {
  if (req.params.id === '0') return next('route')
  res.send(`User ${req.params.id}`)
})

app.get('/user/:id', (req, res) => res.send('Special user'))

/user/5 prints User 5, and /user/0 prints Special user.

app.route()

When the same path handles several methods, app.route() lets you write the path once and chain the handlers:

app.route('/book')
  .get((req, res) => res.send('Get a book'))
  .post((req, res) => res.send('Add a book'))
  .put((req, res) => res.send('Update the book'))

Split routes with express.Router()

As the app grows you don’t want hundreds of routes in one file. express.Router() creates a group of routes you can mount under a prefix:

// routes/api.js
const express = require('express')
const router = express.Router()

router.get('/status', (req, res) => res.json({ ok: true }))

module.exports = router
// app.js
const api = require('./routes/api')
app.use('/api', api)

Now GET /api/status returns {"ok":true}. Inside the router you write paths relative to the mount point.

A router doesn’t see the parameters of the path it’s mounted on. Pass mergeParams: true to get them:

const comments = express.Router({ mergeParams: true })

comments.get('/', (req, res) => {
  res.send(`Comments for post ${req.params.postId}`)
})

app.use('/posts/:postId/comments', comments)

Without mergeParams, req.params.postId would be undefined here.

Routers also accept caseSensitive: true and strict: true (which makes /foo and /foo/ different routes).

Handle 404 pages

A request that no route matches is not an error in Express, so your error handler won’t catch it. Add a middleware after all your routes:

app.use((req, res) => {
  res.status(404).send('Page not found')
})

It runs only when nothing above it sent a response.

Express 4 vs Express 5 path syntax

Express 5 uses a newer version of the path matching library, and a few things from Express 4 tutorials now throw an error when the app starts:

Express 4Express 5
/files/*/files/*filepath
* (match everything)/{*splat}
/user/:id?/user{/:id}
/user/:id(\\d+)validate req.params.id in the handler, or use a RegExp

For example app.get('/old/*', ...) fails with Missing parameter name at index 6, and app.get('/opt/:id?', ...) fails with Unexpected ? at index 8.

The characters (, ), [, ], ?, + and ! are reserved in string paths. Escape them with \ if you need them as literal characters.

Want me to talk about your product? You can sponsor this site.

Related posts about express: