Discover how a tiny Express feature can save you hours of frustrating code!
Why req.query for query strings in Express? - Purpose & Use Cases
Imagine building a web server that reads user input from the URL like ?name=John&age=30 by manually parsing the URL string every time.
Manually extracting query strings is slow, error-prone, and messy. You have to split strings, handle missing values, and decode characters yourself, which leads to bugs and wasted time.
Express provides req.query which automatically parses the query string into an easy-to-use object, so you can access parameters directly by name without extra work.
const url = req.url; const queryString = url.split('?')[1]; const params = {}; queryString.split('&').forEach(pair => { const [key, value] = pair.split('='); params[key] = decodeURIComponent(value); }); console.log(params.name);
console.log(req.query.name);
This lets you quickly and reliably access user inputs from URLs, making your code cleaner and your server faster to build.
When a user searches on a website with ?search=shoes&color=red, req.query lets you easily get those values to show matching products.
Manually parsing query strings is complicated and error-prone.
req.query gives a simple object with all query parameters.
This saves time and reduces bugs when handling URL inputs.
Practice
req.query represent in an Express app?Solution
Step 1: Understand the role of
req.queryreq.queryholds key-value pairs from the URL query string, which comes after the question mark in a URL.Step 2: Differentiate from other request parts
Body data is accessed viareq.body, headers viareq.headers, and cookies viareq.cookies. So,req.queryis specifically for query parameters.Final Answer:
An object containing URL query parameters sent after the question mark -> Option AQuick Check:
req.query = URL query parameters [OK]
- Confusing query parameters with body data
- Thinking req.query holds headers or cookies
- Assuming req.query is a string instead of an object
id in Express?Solution
Step 1: Identify where query parameters are stored
Query parameters are stored inreq.query, so to get the value ofid, usereq.query.id.Step 2: Differentiate from other request properties
req.paramsis for route parameters,req.bodyis for POST data, andreq.headersis for HTTP headers.Final Answer:
req.query.id -> Option BQuick Check:
Query param 'id' = req.query.id [OK]
- Using req.params for query strings
- Trying to get query data from req.body
- Accessing query params from headers
/search?term=books&page=2?
app.get('/search', (req, res) => {
console.log(req.query.term);
console.log(req.query.page);
res.send('Done');
});Solution
Step 1: Understand the URL query string
The URL has query parameters:term=booksandpage=2. These are accessible viareq.query.termandreq.query.page.Step 2: Check what is logged
The code logsreq.query.termwhich is "books" andreq.query.pagewhich is "2" (strings).Final Answer:
books 2 -> Option CQuick Check:
req.query.term = 'books', req.query.page = '2' [OK]
- Expecting numbers instead of strings
- Confusing query params with route params
- Assuming undefined if query exists
app.get('/items', (req, res) => {
const page = req.query.page;
if (page > 0) {
res.send(`Page number is ${page}`);
} else {
res.send('Invalid page');
}
});Solution
Step 1: Identify the type of req.query.page
Query parameters are strings by default, soreq.query.pageis a string, e.g., "1".Step 2: Understand comparison behavior
Comparing a string with a number using > can lead to unexpected results because string comparison is lexicographic. The code should convertpageto a number first.Final Answer:
req.query.page is a string, so numeric comparison may fail -> Option DQuick Check:
Convert query strings to numbers before numeric checks [OK]
- Not converting query params to numbers
- Assuming req.query.page is a number
- Using req.params instead of req.query incorrectly
sort and limit. If limit is missing or not a positive number, it should default to 10. Which code snippet correctly implements this behavior?Solution
Step 1: Default sort parameter
Usereq.query.sort || 'asc'to default falsy/missing values to 'asc'.Step 2: Validate limit as positive number
Number(req.query.limit) > 0 ? Number(req.query.limit) : 10properly converts, checks positivity (>0), and defaults for missing/undefined/NaN/zero/negative.Step 3: Why others fail
B: No sort default;limit || 10accepts invalid like '-1'. C:parseInt(req.query.limit) || 10accepts negatives ('-1' is truthy). D:req.query.limit > '0'does string comparison, accepts invalid like 'a' ("a" > "0").Final Answer:
Number(req.query.limit) > 0 ? Number(req.query.limit) : 10 -> Option AQuick Check:
Convert and validate query params before use [OK]
- Not converting query params to numbers
- Using || default with parseInt causing wrong defaults
- Comparing strings directly to numbers
Ready to prove it?
Pass the test and this pattern moves unknown
