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
Validating route params and query in Express
📖 Scenario: You are building a simple Express server that handles requests for user profiles. Users can request profiles by user ID and optionally filter the profile details by a query parameter.
🎯 Goal: Create an Express route that validates the route parameter userId to be a number and the query parameter details to be either full or summary. If validation passes, respond with a JSON object showing the received parameters.
📋 What You'll Learn
Create an Express app with a GET route at /user/:userId
Validate that userId is a number
Validate that the query parameter details is either full or summary
Send a JSON response with userId and details if valid
Send a 400 status with an error message if validation fails
💡 Why This Matters
🌍 Real World
Validating route and query parameters is essential in web servers to ensure the server receives expected data and can respond correctly without errors.
💼 Career
Backend developers frequently validate parameters in Express routes to build secure and reliable APIs that handle user input safely.
Progress0 / 4 steps
1
Set up Express app and route
Create an Express app by requiring express and calling express(). Then create a GET route at /user/:userId with a callback function that takes req and res parameters.
Express
Hint
Start by importing Express and creating an app instance. Then add a GET route with the exact path /user/:userId.
2
Extract and validate route parameter userId
Inside the route callback, create a variable called userId and assign it the value of req.params.userId. Then create a variable called isUserIdValid that checks if userId converted to a number is not NaN.
Express
Hint
Use req.params.userId to get the route parameter. Use Number() and isNaN() to check if it is a valid number.
3
Extract and validate query parameter details
Create a variable called details and assign it the value of req.query.details. Then create a variable called isDetailsValid that checks if details is either full or summary.
Express
Hint
Use req.query.details to get the query parameter. Check if it equals 'full' or 'summary'.
4
Send response based on validation
Add an if statement that checks if both isUserIdValid and isDetailsValid are true. If so, respond with status 200 and JSON containing userId and details. Otherwise, respond with status 400 and JSON with an error message. Finally, add app.listen(3000) to start the server.
Express
Hint
Use an if to check both validations. Use res.status().json() to send JSON responses. Don't forget to start the server with app.listen(3000).
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
Step 1: Understand the role of validation
Validation checks if the data coming from the user is correct and safe to use.
Step 2: Identify the benefits of validation
It prevents errors in the app and protects against malicious input that could cause security problems.
Final Answer:
To ensure the data is correct and prevent errors or security issues -> Option C
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
Step 1: Recall Express request object properties
Route parameters are accessed via req.params.
Step 2: Match the parameter name
To get the id parameter, use req.params.id.
Final Answer:
req.params.id -> Option D
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
Step 1: Understand the regex validation
The regex ^\d+$ matches only digits from start to end.
Step 2: Check the input against regex
The input abc123 contains letters, so it fails the test.
Step 3: Identify the response on failure
The code returns status 400 with message 'Invalid ID' when validation fails.
Final Answer:
Invalid ID -> Option B
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
Step 1: Analyze the validation logic
If term is missing or too short, it sends a 400 response.
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.
Step 3: Identify the error caused
Sending two responses causes an error about headers already sent.
Final Answer:
It does not return after sending 400 response, causing headers error -> Option A
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
Step 1: Validate userId as digits string
uses regex ^\d+$ on req.params.userId, correctly checking it is numeric string.
Step 2: Validate active query param as 'true' or 'false'
checks active equals 'true' or 'false' strings, returning 400 if not.
Step 3: Confirm proper returns after errors
uses return after sending 400 responses, preventing multiple sends.
Final Answer:
Correctly validates both parameters and returns errors properly -> Option A