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

Payal PorwalPayal Porwal
4 min read

🧠 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

FeaturePurpose
:idRoute param to access dynamic ID
req.queryQuery param to filter/search
req.paramsGet value from :id in route
MiddlewareRun custom logic before sending response

πŸ“Š Real-Life Use Cases

Use CaseFeature Used
Get product by IDRoute params (/product/:id)
Filter users by location or nameQuery params (?city=delhi)
Logging user actions on every routeMiddleware

❓ 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

  1. Add new route: /students/:id/grade β†’ Return dummy grade

  2. Use query param to filter students by name

  3. Create a middleware that counts how many times /students is called


βœ… Final Summary

TopicCovered 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. πŸš€

0
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! 🌟