Day 13: Route Params, Query Params & Middleware in Express.js

Table of contents
- π§ What Youβll Learn
- π 1. What are Route Parameters?
- π 2. What are Query Parameters?
- π 3. What is Middleware?
- π§ Letβs Build a Real-Life Example (Student API)
- π§ͺ Try These in Browser/Postman
- π§ Summary of What You Used
- π Real-Life Use Cases
- β FAQs
- π Practice for Students
- β Final Summary
- π Stay Connected
π§ What Youβll Learn
What are route parameters?
What are query parameters?
What is middleware in Express?
Real-life project: Filtering and accessing student info
Full code with explanation
FAQs
π 1. What are Route Parameters?
Route parameters are dynamic values in the URL.
π§Ύ Example:
GET /students/5
Here, 5
is a route parameter (student ID).
app.get("/students/:id", (req, res) => {
const id = req.params.id;
res.send(`You requested student with ID: ${id}`);
});
π 2. What are Query Parameters?
Query parameters are used to filter/search data.
They are sent in URL after a question mark (?).
π§Ύ Example:
GET /students?city=delhi
app.get("/students", (req, res) => {
const city = req.query.city;
res.send(`Filter students from city: ${city}`);
});
π 3. What is Middleware?
Middleware is a function that runs between request and response.
π§Ύ It can be used for:
Logging
Authentication
Validation
Adding extra headers
function logger(req, res, next) {
console.log(`${req.method} ${req.url}`);
next(); // move to next middleware/route
}
app.use(logger); // applied to all routes
π§ Letβs Build a Real-Life Example (Student API)
Weβll add:
Route param: Get student by
id
Query param: Filter students by
city
Middleware: Log every request
π Folder Structure
express-routing/
βββ index.js
β Step 1: Setup Project
mkdir express-routing
cd express-routing
npm init -y
npm install express
β
Step 2: Create index.js
const express = require("express");
const app = express();
const port = 5000;
// Sample student data
const students = [
{ id: 1, name: "Payal", city: "Delhi" },
{ id: 2, name: "Amit", city: "Mumbai" },
{ id: 3, name: "Ravi", city: "Delhi" },
];
// π§ Middleware to log all requests
app.use((req, res, next) => {
console.log(`${req.method} request on ${req.url}`);
next();
});
// β
Route: Get all students OR filter by city
app.get("/students", (req, res) => {
const city = req.query.city;
if (city) {
const filtered = students.filter((s) => s.city.toLowerCase() === city.toLowerCase());
res.json(filtered);
} else {
res.json(students);
}
});
// β
Route: Get single student by ID
app.get("/students/:id", (req, res) => {
const id = parseInt(req.params.id);
const student = students.find((s) => s.id === id);
if (!student) {
return res.status(404).json({ message: "Student not found" });
}
res.json(student);
});
// Server start
app.listen(port, () => {
console.log(`π Server running on http://localhost:${port}`);
});
π§ͺ Try These in Browser/Postman
β 1. Get all students
GET http://localhost:5000/students
β 2. Filter students by city
GET http://localhost:5000/students?city=delhi
β 3. Get student by ID
GET http://localhost:5000/students/2
π§ Summary of What You Used
Feature | Purpose |
:id | Route param to access dynamic ID |
req.query | Query param to filter/search |
req.params | Get value from :id in route |
Middleware | Run custom logic before sending response |
π Real-Life Use Cases
Use Case | Feature Used |
Get product by ID | Route params (/product/:id ) |
Filter users by location or name | Query params (?city=delhi ) |
Logging user actions on every route | Middleware |
β FAQs
1. Can we use multiple query parameters?
Yes β Example:
/students?city=delhi&age=22
In Express:
const city = req.query.city;
const age = req.query.age;
2. What if ID is not found in route?
Use this check:
if (!student) {
return res.status(404).json({ message: "Student not found" });
}
3. Is middleware optional?
Yes, but it's powerful and often used for:
Logging
Authentication
Error handling
4. Can I apply middleware to specific routes only?
Yes β
app.get("/students", myMiddleware, (req, res) => { ... });
5. What happens if I donβt use next()
in middleware?
Your app will hang and never reach the route handler.
Always use next()
to pass control to next handler.
π Practice for Students
Add new route:
/students/:id/grade
β Return dummy gradeUse query param to filter students by name
Create a middleware that counts how many times
/students
is called
β Final Summary
Topic | Covered Today |
Route Parameters | β
:id used in routes |
Query Parameters | β
/students?city=delhi |
Middleware | β Logging request method & URL |
π Stay Connected
If you found this article helpful and want to receive more such beginner-friendly and industry-relevant Node JS notes, tutorials, and project ideas β π© Subscribe to our newsletter by entering your email below.
And if you're someone who wants to prepare for tech interviews while having a little fun and entertainment, π₯ Donβt forget to subscribe to my YouTube channel β Knowledge Factory 22 β for regular content on tech concepts, career tips, and coding insights!
Stay curious. Keep building. π
Subscribe to my newsletter
Read articles from Payal Porwal directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Payal Porwal
Payal Porwal
Hi there, tech enthusiasts! I'm a passionate Software Developer driven by a love for continuous learning and innovation. I thrive on exploring new tools and technologies, pushing boundaries, and finding creative solutions to complex problems. What You'll Find Here On my Hashnode blog, I share: π In-depth explorations of emerging technologies π‘ Practical tutorials and how-to guides π§Insights on software development best practices πReviews of the latest tools and frameworks π‘ Personal experiences from real-world projects. Join me as we bridge imagination and implementation in the tech world. Whether you're a seasoned pro or just starting out, there's always something new to discover! Letβs connect and grow together! π