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

Built-in Middleware in Express.js

Built-in middleware is middleware functionality provided directly by Express.js to perform common tasks in web applications.

Express.js provides built-in middleware to parse incoming request data and serve static files. We can use these functions without installing separate packages for the same basic functionality.

In this tutorial, we will learn about express.json(), express.urlencoded(), and express.static() with practical examples.

1. What Is Built-in Middleware?

Built-in middleware refers to middleware functions included with Express.js. These functions help process requests or serve files without requiring us to write all the functionality from scratch.

JavaScript
const express = require('express');

const app = express();

// Built-in middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static('public'));

In this example, the application registers three built-in middleware functions for JSON parsing, URL-encoded form parsing, and serving static files.

Remember: Middleware should be registered before the routes that need to use its functionality.

2. Types of Built-in Middleware

Middleware Purpose Example Use
express.json() Parses incoming JSON request bodies. Receiving JSON data from an API client.
express.urlencoded() Parses URL-encoded request bodies. Processing HTML form submissions.
express.static() Serves static files from a directory. Serving HTML, CSS, JavaScript, and images.

3. express.json() Middleware

The express.json() middleware parses incoming requests containing JSON data. After parsing, the data becomes available through req.body.

Example:

JavaScript
const express = require('express');

const app = express();

app.use(express.json());

app.post('/user', (req, res) => {
    console.log(req.body);

    res.json({
        message: 'User data received successfully',
        user: req.body
    });
});

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

Send this JSON request:

JSON
{
    "name": "Rahul",
    "age": 25
}

Send a POST request to http://localhost:3000/user with the Content-Type: application/json header.

Example response:

JSON
{
    "message": "User data received successfully",
    "user": {
        "name": "Rahul",
        "age": 25
    }
}
Important: Without JSON parsing middleware, req.body may remain undefined for a JSON request. Always validate incoming data before using it.

4. express.urlencoded() Middleware

The express.urlencoded() middleware parses incoming request bodies encoded in the URL-encoded format. This format is commonly used by HTML forms.

JavaScript
const express = require('express');

const app = express();

app.use(express.urlencoded({ extended: true }));

app.post('/register', (req, res) => {
    const name = req.body.name;
    const email = req.body.email;

    res.send(`Name: ${name}, Email: ${email}`);
});

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

Example HTML form:

HTML
<form action="/register" method="POST">
    <input type="text" name="name" placeholder="Enter name">
    <input type="email" name="email" placeholder="Enter email">
    <button type="submit">Register</button>
</form>

When the form is submitted, Express parses the submitted form values and makes them available through req.body.

Note: The extended: true option allows the URL-encoded parser to support rich objects and arrays. Use the setting appropriate for your application.

5. express.static() Middleware

The express.static() middleware serves static files such as HTML, CSS, JavaScript, images, and other public assets.

Example folder structure:

myapp/
│
├── app.js
└── public/
    ├── index.html
    ├── style.css
    └── script.js

Express application:

JavaScript
const express = require('express');

const app = express();

app.use(express.static('public'));

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

With this configuration, a file named public/index.html can be requested at http://localhost:3000/index.html.

If you want the home URL / to return the index.html file, place that file in the configured static directory.

Remember: The directory name public is a common convention. You can use a different directory name if needed.

6. How Built-in Middleware Works

Client Request

Browser or API client sends a request

↓
Built-in Middleware

Parses request data or serves static files

↓
Route Handler

Processes the request when applicable

↓
Response

Server sends the result to the client

The exact flow depends on the middleware. For example, static middleware may serve a file directly without reaching a route handler.

7. Complete Example Using Built-in Middleware

The following example combines JSON parsing, URL-encoded form parsing, and static file serving in one application.

JavaScript
const express = require('express');

const app = express();

// Parse JSON request bodies
app.use(express.json());

// Parse URL-encoded form bodies
app.use(express.urlencoded({ extended: true }));

// Serve static files from the public directory
app.use(express.static('public'));

app.post('/api/message', (req, res) => {
    res.json({
        message: 'Request processed successfully',
        data: req.body
    });
});

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

Save the code in app.js, install Express with npm install express, and run it using node app.js.

Important Points to Remember

  • express.json() parses JSON request bodies.
  • express.urlencoded() parses URL-encoded form data.
  • express.static() serves files from a directory.
  • Register middleware before routes that depend on it.
  • Parsed request body data is accessed through req.body.
  • Validate user input before processing or saving it.
  • Static middleware may send a response without reaching a route handler.

Summary

Express.js provides built-in middleware for common web application tasks. The JSON parser reads JSON request bodies, the URL-encoded parser processes form submissions, and the static middleware serves public files.

Understanding these functions helps you build Express.js applications that handle incoming data and static resources correctly.