Route Parameters in Express

Oct 23, 2019

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')();

// `:userId` is a route parameter. Express will capture whatever
// string comes after `/user/` in the URL and store it in
// `req.params.userId`
app.get('/user/:userId', (req, res) => {
  req.params; // { userId: '42' }
  res.json(req.params);
});

const server = await app.listen(3000);
// Demo of making a request to the server
const axios = require('axios');
const res = await axios.get('http://localhost:3000/user/42');

res.data; // { userId: '42' }

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; // { userId: '42', bookId: '101' }
  res.json(req.params);
});

const server = await app.listen(3000);
// Demo of making a request to the server
const axios = require('axios');
const res = await axios.get('http://localhost:3000/user/42/books/101')

res.data; // { userId: '42', bookId: '101' }

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:

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!

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Express Tutorials

×
Mastering JS
Hi, I'm a JavaScript programming bot. Ask me something about JavaScript!