What if a tiny mistake in a URL could crash your app or open a security hole?
Why Validating route params and query in Express? - Purpose & Use Cases
Start learning this pattern below
Jump into concepts and practice - no test required
Imagine building a web app where users type URLs with parameters and queries, like /user/123?age=twenty. You try to handle these inputs manually in your code.
Manually checking every parameter and query is slow and messy. You might forget to check some inputs, causing bugs or security holes. It's easy to accept wrong or harmful data without realizing.
Validating route params and query automatically checks inputs before your code uses them. It stops bad data early, keeps your app safe, and makes your code cleaner and easier to read.
const age = req.query.age; if (!age || isNaN(age)) { res.status(400).send('Invalid age'); }
app.get('/user/:id', validate({ params: idSchema, query: ageSchema }), (req, res) => { // safe to use req.params.id and req.query.age });
You can trust your route parameters and queries are correct, so your app runs smoothly and securely without extra checks everywhere.
When users sign up or search with filters, validating their input in the URL prevents errors and protects your app from bad or malicious data.
Manual input checks are error-prone and repetitive.
Validation stops bad data before it causes problems.
Cleaner code and safer apps with automatic param and query validation.
Practice
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 CQuick Check:
Validation = prevent errors and security risks [OK]
- Thinking validation speeds up the server
- Confusing validation with UI rendering
- Believing validation changes URLs automatically
id in Express?Solution
Step 1: Recall Express request object properties
Route parameters are accessed viareq.params.Step 2: Match the parameter name
To get theidparameter, usereq.params.id.Final Answer:
req.params.id -> Option DQuick Check:
Route params = req.params [OK]
- Using req.query for route params
- Trying to get params from req.body without POST data
- Using req.route which is not for params
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?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 inputabc123contains 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 BQuick Check:
Non-digit ID triggers 400 error [OK]
- Assuming letters pass the digit-only regex
- Expecting 404 instead of 400 error
- Thinking it returns the ID even if invalid
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?
Solution
Step 1: Analyze the validation logic
Iftermis missing or too short, it sends a 400 response.Step 2: Check flow after sending response
There is noreturnafterres.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 AQuick Check:
Always return after sending error response [OK]
- Missing return after res.send causes crash
- Confusing req.params with req.query
- Thinking GET cannot have query params
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?Solution
Step 1: Validate userId as digits string
uses regex^\d+$onreq.params.userId, correctly checking it is numeric string.Step 2: Validate active query param as 'true' or 'false'
checksactiveequals 'true' or 'false' strings, returning 400 if not.Step 3: Confirm proper returns after errors
usesreturnafter sending 400 responses, preventing multiple sends.Final Answer:
Correctly validates both parameters and returns errors properly -> Option AQuick Check:
Regex + strict string checks + return after error = correct [OK]
- Not returning after res.status(400).send
- Checking query params in req.params
- Using loose type checks instead of strict string comparison
