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')();
// `: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:
- A route parameter is never
null
orundefined
. For example, a request toGET /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.
Espresso supports:
- Route handlers, like `app.get()` and `app.post()`
- Express-compatible middleware, like `app.use(require('cors')())`
- Express 4.0 style subrouters
Get the tutorial and master Express today!