Skip to content

Query Strings

Query strings are for extra baggage. They don’t change the route path itself (the destination), but they carry extra info. We know, the stuff after the ? in a URL.

A futuristic open trunk of a cyberpunk sports car containing glowing holographic luggage with digital tags reading ?sort=desc and ?keyword=turbo.

Fig 1: The Luggage.

http://localhost:3000/search?keyword=turbo&sort=desc

In standard HTTP parsing, we’d have to split this string manually. Express, being the luxury vehicle it is, parses these automatically into req.query.

app.get('/search', (req, res) => {
const { keyword, sort } = req.query;
// req.query = { keyword: 'turbo', sort: 'desc' }
if (!keyword) {
return res.send('Please specify a keyword.');
}
res.send(`Searching for ${keyword} sorted by ${sort}`);
});
  • Params (:id): Essential to the resource. The ID defines what we are fetching. (The Destination).
  • Query (?sort=desc): Optional modifiers. Filtering, sorting, pagination. (The Luggage).

If we don’t send a query string, req.query is just an empty object. No baggage, no problem.

1. Route Matching: Query strings are not part of the route path matching.

  • Request: /search?q=pizza
  • Route: app.get('/search', ...)
  • Result: Match. Express ignores the query string when finding the right handler.

2. Common Use Cases:

  • Filtering: ?category=shoes&color=red
  • Sorting: ?sort=price_asc
  • Pagination: ?page=2&limit=20
  • Search: ?q=cyberpunk

Express Query Strings - Demo Repo

Mastering JS: Query Params

⏭ Traffic Types

Are we picking up or dropping off? Time to sort traffic by HTTP Method.