req.query lets you get information sent in the URL after a question mark. This helps your app understand what the user wants without changing the page.
req.query for query strings in Express
req.query.propertyName
req.query is an object containing all query string parameters as key-value pairs.
Each property corresponds to a parameter name in the URL.
app.get('/search', (req, res) => { const term = req.query.term; res.send(`You searched for: ${term}`); });
app.get('/items', (req, res) => { const page = req.query.page || 1; res.send(`Page number: ${page}`); });
app.get('/filter', (req, res) => { const color = req.query.color; const size = req.query.size; res.send(`Filter by color: ${color}, size: ${size}`); });
This simple server listens on port 3000. When you visit /greet?name=Alice, it says 'Hello, Alice!'. If no name is given, it says 'Hello, Guest!'.
import express from 'express'; const app = express(); const port = 3000; app.get('/greet', (req, res) => { const name = req.query.name || 'Guest'; res.send(`Hello, ${name}!`); }); app.listen(port, () => { console.log(`Server running at http://localhost:${port}`); });
Query string values are always strings. Convert them if you need numbers.
If a query parameter is missing, its value will be undefined.
Use default values to avoid errors when parameters are missing.
req.query reads data sent in the URL after the question mark.
It helps your app respond differently based on user input in the URL.
Always check if query parameters exist before using them.
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
