Bird
Raised Fist0
Expressframework~20 mins

Validating route params and query in Express - Practice Problems & Coding Challenges

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
Challenge - 5 Problems
🎖️
Route Validator Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output when accessing /user/42 with valid params?
Consider this Express route that validates a numeric user ID from the route params and a 'role' query parameter. What will the server respond with when the URL is /user/42?role=admin?
Express
const express = require('express');
const app = express();

app.get('/user/:id', (req, res) => {
  const id = Number(req.params.id);
  const role = req.query.role;
  if (isNaN(id) || id <= 0) {
    return res.status(400).send('Invalid user ID');
  }
  if (!role || (role !== 'admin' && role !== 'user')) {
    return res.status(400).send('Invalid role');
  }
  res.send(`User ID: ${id}, Role: ${role}`);
});
AInvalid user ID
BUser ID: 42, Role: admin
CInvalid role
DInternal Server Error
Attempts:
2 left
💡 Hint
Check how the route extracts and validates params and query values.
📝 Syntax
intermediate
2:00remaining
Which option causes a syntax error in route param validation?
Which of the following Express route handlers contains a syntax error when trying to validate a numeric route param 'id'?
Express
const express = require('express');
const app = express();
Aapp.get('/item/:id', (req, res) => { const id = Number(req.params.id); if (id < 0) { res.send('Invalid'); } else { res.send('Valid'); } });
Bapp.get('/item/:id', (req, res) => { const id = Number(req.params.id); if (isNaN(id)) res.send('Invalid'); else res.send('Valid'); });
Capp.get('/item/:id', (req, res) => { const id = Number(req.params.id); if isNaN(id) { res.send('Invalid'); } else { res.send('Valid'); } });
Dapp.get('/item/:id', (req, res) => { const id = Number(req.params.id); if (!id) res.send('Invalid'); else res.send('Valid'); });
Attempts:
2 left
💡 Hint
Look closely at the syntax of the if statement.
state_output
advanced
2:00remaining
What is the response when query param is missing?
Given this Express route that expects a 'page' query parameter as a positive integer, what will the server respond with when the URL is /search (no query params)?
Express
app.get('/search', (req, res) => {
  const page = Number(req.query.page);
  if (!page || page < 1) {
    return res.status(400).send('Page query param required and must be positive');
  }
  res.send(`Page number: ${page}`);
});
APage query param required and must be positive
BPage number: 0
CPage number: NaN
DInternal Server Error
Attempts:
2 left
💡 Hint
Consider what happens when req.query.page is undefined.
🔧 Debug
advanced
2:00remaining
Why does this route always return 'Invalid ID' even for valid numeric IDs?
Examine this Express route. It should accept numeric IDs but always returns 'Invalid ID'. What is the cause?
Express
app.get('/product/:id', (req, res) => {
  const id = req.params.id;
  if (typeof id !== 'number') {
    return res.send('Invalid ID');
  }
  res.send(`Product ID: ${id}`);
});
AThe id variable is not declared properly
BThe route path is incorrect and does not match requests
CThe res.send call is missing parentheses
Dreq.params.id is always a string, so typeof id !== 'number' is always true
Attempts:
2 left
💡 Hint
Check the type of route params in Express.
🧠 Conceptual
expert
3:00remaining
Which validation approach correctly handles optional query params with defaults?
You want to validate an optional 'limit' query parameter that defaults to 10 if missing or invalid. Which code snippet correctly implements this in Express?
A
const limit = parseInt(req.query.limit) || 10;
if (limit &lt;= 0) return res.status(400).send('Limit must be positive');
B
const limit = req.query.limit ?? 10;
if (typeof limit !== 'number') return res.status(400).send('Limit must be a number');
C
const limit = Number(req.query.limit);
if (!limit) limit = 10;
if (limit &lt; 1) return res.status(400).send('Limit must be positive');
D
const limit = Number(req.query.limit) || 10;
if (limit &lt; 1) return res.status(400).send('Limit must be positive');
Attempts:
2 left
💡 Hint
Consider how to parse and default numeric query params safely.

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