Query Strings

Read optional key=value pairs after the ? in a URL from req.query.

Syntaxreq.query.keyName

A query string is the part of a URL after ?, such as /search?term=express&page=2. It is used for optional data like filters, search terms and pagination.

Express parses it for you into the req.query object. Every value is a string (or an array if a key repeats).

Example

Example · javascript
// Request: /search?term=express&page=2
app.get('/search', (req, res) => {
  const term = req.query.term;      // 'express'
  const page = req.query.page || 1; // '2'
  res.send(`Searching '${term}', page ${page}`);
});

When to use it

  • A product listing page reads ?category=shoes&sort=price from the URL to filter and order results from the database.
  • A search endpoint at /search?q=express+tutorial parses the q parameter and returns matching articles.
  • A pagination API reads ?page=2&limit=20 from query strings to return the correct slice of records.

More examples

Reading a single query param

Reads the q query parameter from req.query and returns a 400 error if it is absent.

Example · js
app.get('/search', (req, res) => {
  const { q } = req.query;
  if (!q) return res.status(400).json({ error: 'q is required' });
  res.json({ query: q });
});

Pagination with multiple query params

Parses page and limit query parameters and computes the SQL offset for cursor-based pagination.

Example · js
app.get('/items', (req, res) => {
  const page  = parseInt(req.query.page)  || 1;
  const limit = parseInt(req.query.limit) || 10;
  const offset = (page - 1) * limit;
  res.json({ page, limit, offset });
});

Filtering with multiple params

Destructures multiple optional query parameters and builds a filter object conditionally to pass to a database query.

Example · js
app.get('/products', (req, res) => {
  const { category, minPrice, maxPrice, sort } = req.query;
  // Build a DB query from the parsed params
  const filter = {
    ...(category && { category }),
    ...(minPrice  && { price: { $gte: Number(minPrice) } }),
    ...(maxPrice  && { price: { $lte: Number(maxPrice) } }),
  };
  res.json({ filter, sort: sort || 'default' });
});

Discussion

  • Be the first to comment on this lesson.
Query Strings — Express | SoundsCode