Bird
Raised Fist0
Expressframework~10 mins

req.query for query strings in Express - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - req.query for query strings
Client sends URL with query string
↓
Express server receives request
↓
Express parses URL
↓
Extract query string part
↓
Parse query string into key-value pairs
↓
Store pairs in req.query object
↓
Route handler accesses req.query
↓
Use query values in response
This flow shows how Express takes the query string from a URL, parses it into an object, and makes it available as req.query for route handlers to use.
Execution Sample
Express
app.get('/search', (req, res) => {
  const term = req.query.term;
  res.send(`You searched for: ${term}`);
});
This code reads the 'term' query parameter from the URL and sends it back in the response.
Execution Table
StepActionInput URLreq.query ContentOutput/Response
1Client sends request/search?term=books{}No response yet
2Express receives request/search?term=books{}No response yet
3Parse query string/search?term=books{ term: 'books' }No response yet
4Route handler reads req.query.term/search?term=books{ term: 'books' }Reads 'books'
5Send response/search?term=books{ term: 'books' }You searched for: books
6Request complete/search?term=books{ term: 'books' }Response sent
💡 Request ends after response is sent to client
Variable Tracker
VariableStartAfter Step 3After Step 4Final
req.query{}{ term: 'books' }{ term: 'books' }{ term: 'books' }
termundefinedundefined'books''books'
Key Moments - 3 Insights
Why is req.query an object and not a string?
Because Express parses the query string into key-value pairs and stores them as properties in req.query, as shown in step 3 of the execution_table.
What happens if the URL has no query string?
req.query will be an empty object {}, so accessing any property like req.query.term will be undefined, as no keys exist.
Can req.query have multiple keys?
Yes, if the URL has multiple query parameters like ?term=books&page=2, req.query will have both keys: { term: 'books', page: '2' }.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 3. What does req.query contain after parsing?
A{ term: 'books' }
B'term=books'
Cundefined
D{}
💡 Hint
Check the 'req.query Content' column at step 3 in the execution_table.
At which step does the route handler read the query parameter value?
AStep 2
BStep 4
CStep 3
DStep 5
💡 Hint
Look at the 'Action' column describing when req.query.term is accessed.
If the URL was /search with no query string, what would req.query.term be?
A'search'
Bnull
Cundefined
D{}
💡 Hint
Refer to key_moments about empty query strings and variable_tracker for req.query.
Concept Snapshot
req.query holds query string parameters as an object.
Express parses URL query strings automatically.
Access parameters by name, e.g., req.query.term.
If no query string, req.query is empty {}.
Use in route handlers to customize responses.
Full Transcript
When a client sends a URL with a query string like /search?term=books, Express receives the request and parses the URL. It extracts the query string part after the question mark and converts it into an object with key-value pairs. This object is stored in req.query. For example, req.query will be { term: 'books' }. The route handler can then access req.query.term to get the value 'books' and use it to send a response. If the URL has no query string, req.query will be an empty object, so accessing any key will give undefined. This process allows servers to read extra information from URLs easily and respond accordingly.

Practice

(1/5)
1. What does req.query represent in an Express app?
easy
A. An object containing URL query parameters sent after the question mark
B. The body data sent in a POST request
C. The headers of the HTTP request
D. The cookies sent by the client

Solution

  1. Step 1: Understand the role of req.query

    req.query holds key-value pairs from the URL query string, which comes after the question mark in a URL.
  2. Step 2: Differentiate from other request parts

    Body data is accessed via req.body, headers via req.headers, and cookies via req.cookies. So, req.query is specifically for query parameters.
  3. Final Answer:

    An object containing URL query parameters sent after the question mark -> Option A
  4. Quick Check:

    req.query = URL query parameters [OK]
Hint: Remember: query = URL after '?' [OK]
Common Mistakes:
  • Confusing query parameters with body data
  • Thinking req.query holds headers or cookies
  • Assuming req.query is a string instead of an object
2. Which of the following is the correct way to access a query parameter named id in Express?
easy
A. req.params.id
B. req.query.id
C. req.body.id
D. req.headers.id

Solution

  1. Step 1: Identify where query parameters are stored

    Query parameters are stored in req.query, so to get the value of id, use req.query.id.
  2. Step 2: Differentiate from other request properties

    req.params is for route parameters, req.body is for POST data, and req.headers is for HTTP headers.
  3. Final Answer:

    req.query.id -> Option B
  4. Quick Check:

    Query param 'id' = req.query.id [OK]
Hint: Query params always use req.query.[name] [OK]
Common Mistakes:
  • Using req.params for query strings
  • Trying to get query data from req.body
  • Accessing query params from headers
3. Given this Express route handler, what will be logged if the URL is /search?term=books&page=2?
app.get('/search', (req, res) => {
  console.log(req.query.term);
  console.log(req.query.page);
  res.send('Done');
});
medium
A. term\npage
B. undefined\nundefined
C. books\n2
D. books\nundefined

Solution

  1. Step 1: Understand the URL query string

    The URL has query parameters: term=books and page=2. These are accessible via req.query.term and req.query.page.
  2. Step 2: Check what is logged

    The code logs req.query.term which is "books" and req.query.page which is "2" (strings).
  3. Final Answer:

    books 2 -> Option C
  4. Quick Check:

    req.query.term = 'books', req.query.page = '2' [OK]
Hint: Query values come as strings from req.query [OK]
Common Mistakes:
  • Expecting numbers instead of strings
  • Confusing query params with route params
  • Assuming undefined if query exists
4. What is the problem with this Express route handler?
app.get('/items', (req, res) => {
  const page = req.query.page;
  if (page > 0) {
    res.send(`Page number is ${page}`);
  } else {
    res.send('Invalid page');
  }
});
medium
A. res.send cannot be called inside an if statement
B. req.query.page is undefined, causing a crash
C. The route should use req.params instead of req.query
D. req.query.page is a string, so numeric comparison may fail

Solution

  1. Step 1: Identify the type of req.query.page

    Query parameters are strings by default, so req.query.page is a string, e.g., "1".
  2. 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 convert page to a number first.
  3. Final Answer:

    req.query.page is a string, so numeric comparison may fail -> Option D
  4. Quick Check:

    Convert query strings to numbers before numeric checks [OK]
Hint: Convert query strings to numbers before numeric comparisons [OK]
Common Mistakes:
  • Not converting query params to numbers
  • Assuming req.query.page is a number
  • Using req.params instead of req.query incorrectly
5. You want to create an Express route that reads optional query parameters sort and limit. If limit is missing or not a positive number, it should default to 10. Which code snippet correctly implements this behavior?
hard
A. app.get('/data', (req, res) => { const sort = req.query.sort || 'asc'; const limit = Number(req.query.limit) > 0 ? Number(req.query.limit) : 10; res.send(`Sort: ${sort}, Limit: ${limit}`); });
B. app.get('/data', (req, res) => { const sort = req.query.sort; const limit = req.query.limit || 10; res.send(`Sort: ${sort}, Limit: ${limit}`); });
C. app.get('/data', (req, res) => { const sort = req.query.sort ?? 'desc'; const limit = parseInt(req.query.limit) || 10; res.send(`Sort: ${sort}, Limit: ${limit}`); });
D. app.get('/data', (req, res) => { const sort = req.query.sort || 'desc'; const limit = req.query.limit > '0' ? req.query.limit : 10; res.send(`Sort: ${sort}, Limit: ${limit}`); });

Solution

  1. Step 1: Default sort parameter

    Use req.query.sort || 'asc' to default falsy/missing values to 'asc'.
  2. Step 2: Validate limit as positive number

    Number(req.query.limit) > 0 ? Number(req.query.limit) : 10 properly converts, checks positivity (>0), and defaults for missing/undefined/NaN/zero/negative.
  3. Step 3: Why others fail

    B: No sort default; limit || 10 accepts invalid like '-1'. C: parseInt(req.query.limit) || 10 accepts negatives ('-1' is truthy). D: req.query.limit > '0' does string comparison, accepts invalid like 'a' ("a" > "0").
  4. Final Answer:

    Number(req.query.limit) > 0 ? Number(req.query.limit) : 10 -> Option A
  5. Quick Check:

    Convert and validate query params before use [OK]
Hint: Always convert and validate query params before use [OK]
Common Mistakes:
  • Not converting query params to numbers
  • Using || default with parseInt causing wrong defaults
  • Comparing strings directly to numbers
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard