Master Node.js From Scratch

Clear, interactive, and structured Node.js lessons designed for beginners and developers.

COURSE SYLLABUS
1. Introduction to Node.js
Introduction to Node.js What Is Node.js? Node.js Architecture Features of Node.js Node.js vs Browser JavaScript Node.js Use Cases
2. Installation and Setup
Installation Introduction LTS and Current Versions npm Setup Environment Setup Verify Installation Node.js REPL
3. Node.js Fundamentals
Fundamentals Introduction Running JavaScript Global Objects Process Object Command-Line Arguments Environment Variables
4. JavaScript Basics
JavaScript Basics Introduction Variables: var, let and const JavaScript Data Types Comparison and Logical Operators If, Else If, Else and Switch Loops and Iteration Functions and Arrow Functions JavaScript Array Methods
5. Node.js Modules
Modules Introduction CommonJS Modules ES Modules Export and Import Built-in Modules Creating Custom Modules Path Module OS Module
6. Working with JSON
JSON Introduction JSON Syntax JSON.stringify() JSON.parse() JSON Array of Objects JSON User Database
7. Node Package Manager
npm Introduction package.json Installing Packages Dependencies and DevDependencies npm Scripts Package Versions and Semantic Versioning npm init and Project Setup
8. File System
File System Introduction Reading Files Writing Files Appending Files Deleting Files Working with Directories
9. CLI Applications
CLI Applications Introduction Command-Line Input Task Manager Project Structure Reading todos.json Adding, Updating and Deleting Tasks Saving Tasks to JSON
10. Events and EventEmitter
Events Introduction EventEmitter Registering Events Emitting Events Removing Event Listeners Custom Events
11. Asynchronous Programming
Async Programming Introduction Callbacks Promises async and await setTimeout() and setInterval() Event Loop and Non-Blocking I/O
12. Native HTTP Module
HTTP Module Introduction Creating an HTTP Server Handling Requests Sending Responses HTTP Request Methods Status Codes and Headers Handling POST Request Body Parsing Incoming JSON Products JSON API
13. Express.js
Express.js Introduction Installing Express Creating an Express Server Request and Response Objects Route Parameters and Query Strings Serving Static Files
14. Express Middleware
Middleware Introduction Built-in Middleware Application-Level Middleware Router-Level Middleware Custom Middleware Error-Handling Middleware
15. REST API Development
REST API Introduction GET Endpoints POST Endpoints PUT and PATCH Endpoints DELETE Endpoints Request Validation and API Responses
16. Database Integration
Database Introduction MySQL Integration MongoDB Integration Database CRUD Operations Database Queries and Filtering Connection Management
17. Authentication and Authorization
Authentication Introduction Password Hashing User Registration User Login JWT Authentication Authorization and Protected Routes
18. Advanced Node.js
Advanced Node.js Introduction Error Handling Debugging Node.js Applications Streams Buffers Performance and Security

Route Parameters in Express.js

Learn how to define dynamic routes, capture values from URLs and access route parameters using req.params in Express.js.

When a user opens a website, the URL may contain an ID, product name or another value. For example, a student wants to view student details using a student ID. Instead of creating a separate route for every student, Express.js allows us to create one dynamic route using route parameters.

Express.js captures the values from the URL and makes them available through the request object's req.params property.

1. What Are Route Parameters?

Route parameters are named values included in a route URL. They help us create dynamic routes that can handle different values using the same route definition.

For example, consider the following URLs for viewing student details.

Example URLs
/students/101
/students/102
/students/103

We can handle all these URLs using one route: /students/:id. Here, :id is a route parameter that captures the student ID from the URL.

Remember: The colon (:) defines a named route parameter. We access its value using req.params.

2. Why Do We Use Route Parameters?

Route parameters make routes reusable. We do not need to create a separate route for every student, product or user.

Scenario Example URL Purpose
Student details /students/101 Access a student using an ID.
Product details /products/501 Access a product using an ID.
User profile /users/pradnya Access a user profile by username.
Employee details /employees/201 Access an employee using an ID.

Each URL can be handled by a dynamic route instead of creating a different route for every value.

3. Basic Syntax of Route Parameters

The following example defines a route with an ID parameter and sends that ID back to the client.

JavaScript
app.get("/students/:id", (req, res) => {

    const studentId = req.params.id;

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

});

Understanding the Code

Code Explanation
app.get() Defines a route that handles GET requests.
/students/:id Defines a route with a dynamic ID parameter.
req Represents the incoming HTTP request.
req.params Contains the values captured from route parameters.
req.params.id Reads the value of the parameter named id.
res.send() Sends the response to the client.
Important: Route parameter values are normally received as strings. If you need a number, convert and validate the value before using it in your application logic.

4. How Do Route Parameters Work?

When the client requests a URL, Express.js matches it against the route definition. If the route matches, Express.js extracts the parameter values and provides them through req.params.

1. Client Request

Requests /students/101.

↓
2. Match Route

Express matches /students/:id.

↓
3. Capture Parameter

req.params.id contains "101".

↓
4. Send Response

The client receives Student ID: 101.

5. First Program: Using a Single Route Parameter

Let's create a simple Express.js server that accepts a student ID from the URL and displays it in the response.

Step 1: Create app.js

JavaScript
const express = require("express");

const app = express();

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

    const studentId = req.params.id;

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

});

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

Step 2: Install Express.js

Open the terminal in your project folder and run the following commands if Express.js is not already installed.

Terminal
npm init -y
npm install express

Step 3: Run the Server

Terminal
node app.js

Step 4: Open the URL

URL
http://localhost:3000/students/101

Expected Browser Output

Output
Student ID: 101

Explanation: The value 101 is captured by the route parameter :id. The code reads it using req.params.id and sends it back to the browser.

If you change the URL to http://localhost:3000/students/202, the response will be Student ID: 202. The same route handles both requests.

6. Using Multiple Route Parameters

Express.js allows us to define multiple named parameters in a single route. For example, we can capture both a student's ID and name from the URL.

Example: Student ID and Name

JavaScript
app.get("/students/:id/:name", (req, res) => {

    const studentId = req.params.id;
    const studentName = req.params.name;

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

});

Test URL

URL
http://localhost:3000/students/101/Pradnya

Expected Browser Output

Output
Student ID: 101, Student Name: Pradnya

Understanding the Parameters

Route Parameter URL Value Access Code
:id 101 req.params.id
:name Pradnya req.params.name
Remember: The parameter names in req.params must match the names defined in the route.

7. Example: Product Route Parameters

Route parameters are also useful when displaying product details. In this example, the route captures a category and a product ID.

Example Code

JavaScript
app.get("/products/:category/:id", (req, res) => {

    const category = req.params.category;
    const productId = req.params.id;

    res.send(
        `Category: ${category}, Product ID: ${productId}`
    );

});

Test URL

URL
http://localhost:3000/products/mobile/501

Expected Browser Output

Output
Category: mobile, Product ID: 501

Explanation: The first parameter captures mobile as the category. The second parameter captures 501 as the product ID.

8. Validating Route Parameters

Route parameter values are received as strings. If our application expects a numeric ID, we should convert the value and validate it before using it.

Example: Validate a Student ID

JavaScript
app.get("/students/:id", (req, res) => {

    const studentId = Number(req.params.id);

    if (!Number.isInteger(studentId) || studentId <= 0) {

        return res.status(400).send("Invalid student ID");

    }

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

});

Test URL 1: Valid ID

URL
http://localhost:3000/students/10
Expected Output
Student ID: 10

Test URL 2: Invalid ID

URL
http://localhost:3000/students/abc
Expected Response — HTTP 400
Invalid student ID

Explanation: Number() converts the route parameter into a number. Number.isInteger() checks whether the result is an integer, and the condition rejects zero, negative values and non-numeric input.

Important: Validate user-provided route parameters before using them in database queries or other application operations.

9. Route Parameters vs Query Parameters

Route parameters and query parameters both carry values in a URL, but Express.js provides different properties to access them.

Route Parameters Query Parameters
Accessed using req.params. Accessed using req.query.
Defined with a colon in the route. Provided after the ? in the URL.
/students/101 /students?id=101
Route: /students/:id Route: /students
req.params.id req.query.id
Easy Trick:
  • /students/101 → Route parameter → req.params
  • /students?id=101 → Query parameter → req.query

10. Important Points

  • Route parameters make Express.js routes dynamic and reusable.
  • Use a colon (:) to define a named route parameter.
  • Use req.params to access route parameter values.
  • Parameter names must match the names defined in the route.
  • Route parameter values are normally received as strings.
  • Multiple route parameters can be defined in one route.
  • Validate route parameters before processing them.
  • Use req.query for query parameters, not req.params.

Summary

In this lesson, we learned how to define route parameters in Express.js using a colon in the route URL. We accessed parameter values through req.params, created routes with single and multiple parameters, validated a numeric student ID and compared route parameters with query parameters. Route parameters help us build dynamic, reusable routes for students, products, users and other application resources.