Paramclasses Academy - Blog

Tutorials Details

←
Post 18 of 40
→

Express.js Routing Explained with Practical Examples

Express.js Routing Explained with Practical Examples

October 29, 2026

✦ Express.js Routing Explained with Practical Examples

❖ Introduction to Express.js Routing

Express.js is a popular Node.js framework used to build websites, web applications, and REST APIs. One of its most important features is routing. Routing determines how an application responds when a user visits a particular URL or sends an HTTP request.

For example, a website may have different pages and features:

  • / – Home page

  • /about – About page

  • /contact – Contact page

  • /students – Student list

  • /students/10 – Details of a particular student

Express.js routing allows developers to connect these URLs with the appropriate functions.

In this tutorial, we will learn Express.js routing step by step with practical examples suitable for beginners.

✦ What Is Routing in Express.js?

Routing is the process of defining how an application responds to a specific HTTP method and URL path.

A route generally consists of three parts:

  1. HTTP method: Such as GET, POST, PUT, or DELETE.

  2. Route path: The URL pattern that the application matches.

  3. Route handler: The function that runs when the route matches.

For example:

app.get("/about", (req, res) => {
    res.send("Welcome to the About Page");
});

Here:

  • app.get() defines a GET route.

  • /about is the route path.

  • req represents the incoming request.

  • res represents the response sent to the client.

  • res.send() sends a response.

When a browser requests /about using GET, Express executes the matching handler.

✦ Step 1: Install Node.js and Express.js

Before starting, install Node.js and npm on your computer. You can download Node.js from the official website:

https://nodejs.org/

Open your terminal or command prompt and create a project folder.

mkdir express-routing
cd express-routing
npm init -y
npm install express

Create a file named app.js inside the project folder.

Your project structure will look like this:

express-routing/
├── node_modules/
├── app.js
├── package.json
└── package-lock.json

✦ Step 2: Create Your First Express Route

Add the following code to app.js:

const express = require("express");

const app = express();
const PORT = 3000;

app.get("/", (req, res) => {
    res.send("Welcome to My Express.js Website!");
});

app.get("/about", (req, res) => {
    res.send("This is the About Page.");
});

app.get("/contact", (req, res) => {
    res.send("Contact us for more information.");
});

app.listen(PORT, () => {
    console.log(`Server running at http://localhost:${PORT}`);
});

Run the application:

node app.js

Open your browser and visit:

  • http://localhost:3000/

  • http://localhost:3000/about

  • http://localhost:3000/contact

Each URL displays a different response.

✦ Step 3: Understand HTTP Methods in Express.js

HTTP methods describe the type of operation a client wants to perform.

Method Common purpose
GET Retrieve data
POST Submit or create data
PUT Replace or update a resource
PATCH Partially update a resource
DELETE Delete a resource

Example:

app.get("/students", (req, res) => {
    res.send("Display all students");
});

app.post("/students", (req, res) => {
    res.send("Create a new student");
});

app.put("/students/1", (req, res) => {
    res.send("Replace student details");
});

app.patch("/students/1", (req, res) => {
    res.send("Update selected student details");
});

app.delete("/students/1", (req, res) => {
    res.send("Delete student");
});

These routes demonstrate how the same application can handle different operations.

Important: Typing a URL into a browser normally sends a GET request. To test POST, PUT, PATCH, and DELETE routes, use tools such as Postman or an appropriate frontend form or application.

✦ Step 4: Use Route Parameters

Route parameters help capture values directly from a URL.

For example, consider this route:

app.get("/students/:id", (req, res) => {
    const studentId = req.params.id;

    res.send(`Student ID: ${studentId}`);
});

Visit:

http://localhost:3000/students/15

The response will be:

Student ID: 15

In this example, :id is a route parameter. Express makes its value available through req.params.id.

You can use multiple route parameters:

app.get("/courses/:courseId/students/:studentId", (req, res) => {
    const courseId = req.params.courseId;
    const studentId = req.params.studentId;

    res.json({
        courseId: courseId,
        studentId: studentId
    });
});

Example URL:

http://localhost:3000/courses/5/students/15

The response is a JSON object containing both IDs.

Use case: Route parameters are useful for fetching individual student records, product details, blog posts, and user profiles from a database.

✦ Step 5: Understand Query Parameters

Query parameters pass additional information after a question mark (?) in a URL. They are often used for searching, filtering, sorting, and pagination.

Example URL:

http://localhost:3000/search?name=Rahul&course=Node.js

Create this route:

app.get("/search", (req, res) => {
    const name = req.query.name;
    const course = req.query.course;

    res.json({
        studentName: name,
        course: course
    });
});

The response will contain:

{
    "studentName": "Rahul",
    "course": "Node.js"
}

The difference is simple:

  • req.params reads values defined in the route path.

  • req.query reads values provided in the query string.

For example, /students/15 uses a route parameter, while /students?page=2 uses a query parameter.

Query parameters are user-controlled input, so validate them before using them in database queries or business logic.

✦ Step 6: Handle POST Requests and Request Bodies

POST routes are commonly used to submit form data or create records. To read JSON request bodies, enable Express's JSON middleware.

const express = require("express");

const app = express();

app.use(express.json());

app.post("/students", (req, res) => {
    const { name, course } = req.body;

    if (!name || !course) {
        return res.status(400).json({
            message: "Name and course are required"
        });
    }

    res.status(201).json({
        message: "Student data received successfully",
        student: {
            name: name,
            course: course
        }
    });
});

app.listen(3000, () => {
    console.log("Server running on port 3000");
});

In Postman, select POST, enter http://localhost:3000/students, choose Body → raw → JSON, and send:

{
    "name": "Rahul",
    "course": "Node.js"
}

This example validates the required fields and returns a success response. It does not save the student to a database; database integration would be a separate step.

✦ Step 7: Organize Routes Using express.Router()

As an application grows, keeping every route in app.js becomes difficult. Express provides express.Router() to organize related routes into separate files.

Create this structure:

express-routing/
├── routes/
│   └── studentRoutes.js
├── app.js
└── package.json

File: routes/studentRoutes.js

const express = require("express");

const router = express.Router();

router.get("/", (req, res) => {
    res.send("Display all students");
});

router.get("/:id", (req, res) => {
    res.send(`Display student ${req.params.id}`);
});

router.post("/", (req, res) => {
    res.send("Create a student");
});

module.exports = router;

File: app.js

const express = require("express");
const studentRoutes = require("./routes/studentRoutes");

const app = express();

app.use(express.json());

app.use("/students", studentRoutes);

app.listen(3000, () => {
    console.log("Server running at http://localhost:3000");
});

Now the student routes are available at:

  • GET /students

  • GET /students/15

  • POST /students

The app.use("/students", studentRoutes) statement mounts the router under the /students prefix.

This approach makes applications easier to maintain and expand.

✦ Step 8: Handle Invalid Routes with a 404 Response

If a requested URL does not match any route, you can return a custom 404 response.

Place this code after your valid routes:

app.use((req, res) => {
    res.status(404).json({
        message: "Route not found"
    });
});

For example, visiting /unknown-page will return a 404 response if no earlier route matches it.

Routing tip: Define specific routes before broad or catch-all handlers. A handler that sends a response without calling next() generally ends the request-response cycle, so later matching handlers will not run.

✦ Common Express.js Routing Mistakes

Beginners often face these issues:

  1. Incorrect URL: Check the spelling and path of the requested URL.

  2. Wrong HTTP method: A GET route does not automatically handle a POST request.

  3. Incorrect parameter access: Use req.params.id for a route parameter and req.query.id for a query parameter.

  4. Missing JSON middleware: Add app.use(express.json()) before routes that read JSON request bodies.

  5. Incorrect route order: Place specific routes and error-handling middleware appropriately.

  6. No validation: Validate incoming parameters and request bodies before processing them.

  7. Confusing a demo with a complete application: A route that returns a message does not automatically save or retrieve database records.

✦ Frequently Asked Questions (FAQs)

1. What is routing in Express.js?

Routing defines how an Express application responds to HTTP requests for specific URL paths and methods.

2. What is the difference between req.params and req.query?

req.params contains route parameter values, while req.query contains query-string values.

3. What is express.Router()?

It creates a modular router that allows related routes to be grouped into separate files.

4. Can multiple routes use the same URL?

Yes. Different HTTP methods can use the same path, such as GET and POST on /students, to perform different operations.

5. Is Express.js routing useful for REST APIs?

Yes. Routing is a core part of building REST APIs because it connects HTTP requests to application logic.

✦ Conclusion

Express.js routing is an essential skill for Node.js developers. By learning route paths, HTTP methods, route parameters, query parameters, request bodies, and modular routing, beginners can build a clear foundation for developing web applications and REST APIs.

Start with simple routes, test each endpoint, and gradually separate your code into route files. After mastering routing, you can move on to middleware, request validation, database integration, authentication, and complete CRUD applications.

Learn practical web development with Param Classes.

 

←
Post 18 of 40
→