Query Strings
Extra Baggage
Section titled “Extra Baggage”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.
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}`);});The Difference
Section titled “The Difference”- 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.
Rules of the Road
Section titled “Rules of the Road”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
Extra Bits & Bytes
Section titled “Extra Bits & Bytes”Express Query Strings - Demo Repo
Mastering JS: Query Params