Bird
Raised Fist0
Expressframework~10 mins

Validating route params and query in Express - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Validating route params and query
Request received
Extract route params & query
Validate params & query
Proceed
Handle request logic
Send success response
When a request comes in, Express extracts route parameters and query strings, then checks if they are valid before continuing or sending an error.
Execution Sample
Express
app.get('/user/:id', (req, res) => {
  const id = req.params.id;
  const age = req.query.age;
  if (!/^[0-9]+$/.test(id) || (age && isNaN(Number(age)))) {
    return res.status(400).send('Invalid parameters');
  }
  res.send(`User ${id}, age ${age || 'unknown'}`);
});
This code checks if the route param 'id' is all digits and if the optional query 'age' is a number, sending an error if not.
Execution Table
StepActionRoute Param 'id'Query 'age'Validation ResultResponse
1Request: /user/123?age=2512325id valid, age validProceed
2Request: /user/abc?age=25abc25id invalid400 Invalid parameters
3Request: /user/123?age=twenty123twentyage invalid400 Invalid parameters
4Request: /user/456456undefinedid valid, age missing but optionalProceed
5Request: /user/789?age=3078930id valid, age validProceed
6Request: /user/12a?age=3012a30id invalid400 Invalid parameters
💡 Execution stops when validation fails, sending 400 error; otherwise, request proceeds.
Variable Tracker
VariableStartAfter 1After 2After 3After 4After 5After 6
idundefined123abc12345678912a
ageundefined2525twentyundefined3030
validationResultundefinedvalidinvalidinvalidvalidvalidinvalid
responseundefinedproceed400 error400 errorproceedproceed400 error
Key Moments - 3 Insights
Why does the request with id='abc' fail validation?
Because the id param must be digits only, as shown in execution_table row 2 where 'abc' fails the regex test.
Is the 'age' query parameter required for the request to succeed?
No, 'age' is optional. In row 4, age is missing but validation passes because only id is required and valid.
What happens if 'age' is present but not a number?
Validation fails and a 400 error is sent, as in row 3 where age='twenty' is invalid.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the validation result at step 5?
Aage invalid
Bid invalid
Cid valid, age valid
Did valid, age missing
💡 Hint
Check the 'Validation Result' column at row 5 in the execution_table.
At which step does the condition fail because 'id' contains letters?
AStep 2
BStep 1
CStep 4
DStep 5
💡 Hint
Look for 'id invalid' in the 'Validation Result' column in execution_table.
If the regex for 'id' was changed to allow letters, how would step 6 change?
AValidation would still fail due to id
BValidation would pass and response would proceed
CValidation would fail due to age
DNo change, still 400 error
💡 Hint
Refer to variable_tracker for 'id' and 'validationResult' at step 6 and consider regex effect.
Concept Snapshot
Express route params and query validation:
- Extract params via req.params and query via req.query
- Use regex or type checks to validate
- If invalid, send 400 error response
- If valid, proceed with request handling
- Optional query params can be checked conditionally
Full Transcript
When Express receives a request, it extracts route parameters and query strings. The code then checks if these values meet expected formats, like digits only for an id or numeric for age. If validation fails, the server responds with a 400 error and stops processing. If validation passes, the server continues to handle the request and sends a success response. This process ensures only valid data is processed, preventing errors or misuse.

Practice

(1/5)
1. What is the main reason to validate route parameters and query strings in an Express app?
easy
A. To automatically generate HTML pages
B. To speed up the server response time
C. To ensure the data is correct and prevent errors or security issues
D. To change the URL structure dynamically

Solution

  1. Step 1: Understand the role of validation

    Validation checks if the data coming from the user is correct and safe to use.
  2. Step 2: Identify the benefits of validation

    It prevents errors in the app and protects against malicious input that could cause security problems.
  3. Final Answer:

    To ensure the data is correct and prevent errors or security issues -> Option C
  4. Quick Check:

    Validation = prevent errors and security risks [OK]
Hint: Validation protects your app from bad or harmful input [OK]
Common Mistakes:
  • Thinking validation speeds up the server
  • Confusing validation with UI rendering
  • Believing validation changes URLs automatically
2. Which of the following is the correct way to access a route parameter named id in Express?
easy
A. req.route.id
B. req.query.id
C. req.body.id
D. req.params.id

Solution

  1. Step 1: Recall Express request object properties

    Route parameters are accessed via req.params.
  2. Step 2: Match the parameter name

    To get the id parameter, use req.params.id.
  3. Final Answer:

    req.params.id -> Option D
  4. Quick Check:

    Route params = req.params [OK]
Hint: Route params are always in req.params, not req.query [OK]
Common Mistakes:
  • Using req.query for route params
  • Trying to get params from req.body without POST data
  • Using req.route which is not for params
3. Consider this Express route handler:
app.get('/user/:id', (req, res) => {
  const id = req.params.id;
  if (!/^\d+$/.test(id)) {
    return res.status(400).send('Invalid ID');
  }
  res.send(`User ID is ${id}`);
});

What will be the response if the URL is /user/abc123?
medium
A. User ID is abc123
B. Invalid ID
C. 404 Not Found
D. 500 Internal Server Error

Solution

  1. Step 1: Understand the regex validation

    The regex ^\d+$ matches only digits from start to end.
  2. Step 2: Check the input against regex

    The input abc123 contains letters, so it fails the test.
  3. Step 3: Identify the response on failure

    The code returns status 400 with message 'Invalid ID' when validation fails.
  4. Final Answer:

    Invalid ID -> Option B
  5. Quick Check:

    Non-digit ID triggers 400 error [OK]
Hint: Regex test fails non-digit IDs, returns 400 error [OK]
Common Mistakes:
  • Assuming letters pass the digit-only regex
  • Expecting 404 instead of 400 error
  • Thinking it returns the ID even if invalid
4. Given this Express route:
app.get('/search', (req, res) => {
  const { term } = req.query;
  if (!term || term.length < 3) {
    res.status(400).send('Search term too short');
  }
  res.send(`Searching for ${term}`);
});

What is the bug in this code?
medium
A. It does not return after sending 400 response, causing headers error
B. It does not check if term is a string
C. It uses req.params instead of req.query
D. It should use POST method instead of GET

Solution

  1. Step 1: Analyze the validation logic

    If term is missing or too short, it sends a 400 response.
  2. Step 2: Check flow after sending response

    There is no return after res.status(400).send(), so code continues and tries to send another response.
  3. Step 3: Identify the error caused

    Sending two responses causes an error about headers already sent.
  4. Final Answer:

    It does not return after sending 400 response, causing headers error -> Option A
  5. Quick Check:

    Always return after sending error response [OK]
Hint: Return immediately after sending error response [OK]
Common Mistakes:
  • Missing return after res.send causes crash
  • Confusing req.params with req.query
  • Thinking GET cannot have query params
5. You want to validate both a route parameter userId (must be a number) and a query parameter active (must be 'true' or 'false') in Express. Which code snippet correctly validates both and returns 400 errors if invalid?
hard
A. app.get('/user/:userId', (req, res) => { const { userId } = req.params; const { active } = req.query; if (!/^\d+$/.test(userId)) { return res.status(400).send('Invalid userId'); } if (active !== 'true' && active !== 'false') { return res.status(400).send('Invalid active flag'); } res.send(`User ${userId} active: ${active}`); });
B. app.get('/user/:userId', (req, res) => { const userId = Number(req.params.userId); const active = req.query.active === true; if (!userId) { res.status(400).send('Invalid userId'); } if (active !== true && active !== false) { res.status(400).send('Invalid active flag'); } res.send(`User ${userId} active: ${active}`); });
C. app.get('/user/:userId', (req, res) => { const { userId, active } = req.params; if (isNaN(userId)) { return res.status(400).send('Invalid userId'); } if (active !== 'true' || active !== 'false') { return res.status(400).send('Invalid active flag'); } res.send(`User ${userId} active: ${active}`); });
D. app.get('/user/:userId', (req, res) => { const userId = req.params.userId; const active = req.query.active; if (typeof userId !== 'number') { return res.status(400).send('Invalid userId'); } if (active !== 'true' && active !== 'false') { return res.status(400).send('Invalid active flag'); } res.send(`User ${userId} active: ${active}`); });

Solution

  1. Step 1: Validate userId as digits string

    uses regex ^\d+$ on req.params.userId, correctly checking it is numeric string.
  2. Step 2: Validate active query param as 'true' or 'false'

    checks active equals 'true' or 'false' strings, returning 400 if not.
  3. Step 3: Confirm proper returns after errors

    uses return after sending 400 responses, preventing multiple sends.
  4. Final Answer:

    Correctly validates both parameters and returns errors properly -> Option A
  5. Quick Check:

    Regex + strict string checks + return after error = correct [OK]
Hint: Use regex for numbers and strict string checks for query params [OK]
Common Mistakes:
  • Not returning after res.status(400).send
  • Checking query params in req.params
  • Using loose type checks instead of strict string comparison