Query string parsing helps you get information from the URL after the question mark. This lets your app understand what the user wants.
Query string parsing in Express
app.get('/path', (req, res) => { const value = req.query.key; // use value res.send(`Value is ${value}`); });
req.query is an object containing all query parameters as strings.
If a parameter is missing, its value will be undefined.
term parameter from the query string like /search?term=booksapp.get('/search', (req, res) => { const term = req.query.term; res.send(`Search term: ${term}`); });
page is not provided in the URL.app.get('/items', (req, res) => { const page = req.query.page || 1; res.send(`Page number: ${page}`); });
app.get('/filter', (req, res) => { const { category, sort } = req.query; res.send(`Category: ${category}, Sort: ${sort}`); });
This Express app listens on port 3000. When you visit /products?category=books&page=2, it reads the query parameters and shows them in the response.
import express from 'express'; const app = express(); const port = 3000; app.get('/products', (req, res) => { const category = req.query.category || 'all'; const page = Number(req.query.page) || 1; res.send(`Showing products in category: ${category}, page: ${page}`); }); app.listen(port, () => { console.log(`Server running on http://localhost:${port}`); });
Query parameters are always strings. Convert them to numbers or booleans if needed.
Use default values to avoid errors when parameters are missing.
Express automatically parses the query string into req.query.
Query string parsing lets you read extra info from URLs.
Use req.query in Express to get query parameters as an object.
Always handle missing or wrong types by setting defaults or converting values.
Practice
/search?term=books?Solution
Step 1: Understand Express request objects
Express provides different objects to access parts of the request:req.paramsfor route params,req.bodyfor POST data, andreq.queryfor query strings.Step 2: Identify query string access
The query string is the part after?in a URL. Express parses it intoreq.queryas an object.Final Answer:
req.query -> Option AQuick Check:
Query string = req.query [OK]
- Confusing req.params with req.query
- Trying to read query from req.body
- Using req.url directly without parsing
page in an Express route handler?Solution
Step 1: Recall query parameter access syntax
Query parameters are accessed viareq.queryas key-value pairs.Step 2: Match correct syntax
To get thepageparameter, usereq.query.page. Other options access wrong objects.Final Answer:
const page = req.query.page; -> Option AQuick Check:
Query param 'page' = req.query.page [OK]
- Using req.params for query parameters
- Trying to read query from req.body
- Accessing req.url.page which is undefined
app.get('/items', (req, res) => {
const limit = Number(req.query.limit) || 10;
res.send(`Limit is ${limit}`);
});What will be the response if the URL is
/items?limit=5?Solution
Step 1: Convert query string value to number
The code usesNumber(req.query.limit)to convert the string '5' to number 5.Step 2: Use default if conversion fails
If conversion results in 0 or NaN, it defaults to 10. Here, 5 is valid, so limit = 5.Final Answer:
"Limit is 5" -> Option CQuick Check:
Number('5') = 5, so output = "Limit is 5" [OK]
- Not converting string to number
- Assuming req.query.limit is a number
- Ignoring default fallback logic
app.get('/search', (req, res) => {
const term = req.query.term.toLowerCase();
res.send(term);
});What error will occur if the URL is
/search (no query parameter)?Solution
Step 1: Check for missing query parameter
Iftermis missing,req.query.termis undefined.Step 2: Calling method on undefined causes error
CallingtoLowerCase()on undefined throws a TypeError.Final Answer:
TypeError: Cannot read property 'toLowerCase' of undefined -> Option BQuick Check:
Undefined.toLowerCase() throws TypeError [OK]
- Assuming query param always exists
- Not handling undefined values
- Expecting empty string instead of error
sort that can be either asc or desc. If missing or invalid, default to asc. Which code snippet correctly implements this in Express?Solution
Step 1: Validate query parameter value
We must check ifreq.query.sortis either 'asc' or 'desc'. Usingincludes()on an array is a clean way.Step 2: Provide default if invalid or missing
If the value is not in the allowed list, default to 'asc'. This avoids invalid values.Final Answer:
const sort = ['asc', 'desc'].includes(req.query.sort) ? req.query.sort : 'asc'; -> Option DQuick Check:
Check allowed values with includes() and default [OK]
- Not validating allowed values
- Using simple || which accepts invalid strings
- Overcomplicating with nested ternaries
Ready to prove it?
Pass the test and this pattern moves unknown
