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.


More Express Tutorials