Params in Express

Aug 24, 2020

In Express, route parameters are values derived from portions of the URL that start with :. The the req.params property is where Express stores the values of the named sections in the URL.

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' }

Route parameters are also known as URL parameters.

Query String Parameters

Query string params are another commonly used type of parameter in Express. The query string portion of a URL is the part of the URL after the question mark ?.

By default, Express parses the query string and stores the parsed result on the request object as req.query:

const app = require('express')();

app.get('*', (req, res) => {
  req.query; // { a: '1', b: '2' }
  res.json(req.query);
});

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/?a=1&b=2')

res.data; // { a: '1', b: '2' }

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