Route Parameters in Express

Route Parameters in Express

In Express, route parameters are essentially
variables derived from named sections of the URL. Express captures
the value in the named section and stores it in the req.params property.

const

app =

require

(

'express'

)(); app.get(

'/user/:userId'

, (req, res) => { req.params; res.json(req.params); });

const

server =

await

app.listen(

3000

);

const

axios =

require

(

'axios'

);

const

res =

await

axios.get(

'http://localhost:3000/user/42'

); res.data;

You can define multiple route parameters in a URL. In the below example,
the Express route is /users/:userId/books/:bookId, so req.params.userId
will contain the substring after /users/ and before /books/, and req.params.bookId will contain everything after /books/.

const

app =

require

(

'express'

)(); app.get(

'/user/:userId/books/:bookId'

, (req, res) => { req.params; res.json(req.params); });

const

server =

await

app.listen(

3000

);

const

axios =

require

(

'axios'

);

const

res =

await

axios.get(

'http://localhost:3000/user/42/books/101'

) res.data;

Why Route Parameters?

Route parameters have some convenient properties that reduce the amount of
validation you need to do versus using query parameters or request bodies:

  • A route parameter is never null or undefined. For example, a request to GET /users above will cause an HTTP 404, and not call the route handler for /users/:userId/books/:bookId.
  • A route parameter is always a string with positive length. For example, GET /user/42/books/ also causes an HTTP 404.

If you’re defining an HTTP API in Express, it is usually better to make a
parameter a route parameter rather than a query parameter or a body parameter
if possible. If your parameter is mandatory and doesn’t need to be an object,
route parameters are generally the way to go.


Want to become your team’s Express expert? There’s no better way to really grok a framework than to write your own
clone from scratch. In 15 concise pages, this tutorial walks you through how to write a simplified clone of Express
called Espresso.
Get your copy!


Espresso supports:

  • Route handlers, like `app.get()` and `app.post()`
  • Express-compatible middleware, like `app.use(require(‘cors’)())`
  • Express 4.0 style subrouters

As a bonus, Espresso also supports async functions, unlike Express.

Get the tutorial and master Express today!

More Express Tutorials