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

Error-Handling Middleware in Express.js

Error-handling middleware helps an Express.js application handle errors in a centralized and organized way.

During application execution, errors can occur because of invalid input, database failures, missing resources, or unexpected application problems. Instead of writing separate error-handling logic in every route, we can use error-handling middleware.

Express identifies error-handling middleware by its four parameters: err, req, res, and next. It can generate a suitable response and prevent internal error details from being unnecessarily exposed to clients.

1. What Is Error-Handling Middleware?

Error-handling middleware is a special middleware function used to handle errors that occur while processing requests.

Unlike regular middleware, it receives four parameters:

  • err: Contains the error information.
  • req: Contains information about the request.
  • res: Is used to send a response to the client.
  • next: Passes the error to another error handler when needed.
JavaScript
function errorHandler(err, req, res, next) {
    console.error(err.stack);

    res.status(500).json({
        message: 'Something went wrong!'
    });
}

In this example, the middleware logs the error on the server and sends a generic HTTP 500 response to the client.

Remember: Error-handling middleware must have four declared parameters in the correct order. Register it after the routes and middleware whose errors it should handle.

2. Why Do We Need Error-Handling Middleware?

Without centralized error handling, applications can become difficult to maintain because every route may handle failures differently.

Error Situation Example Possible Response
Invalid Input A required field is missing. 400 Bad Request
Missing Resource A requested product does not exist. 404 Not Found
Authentication Failure Valid authentication credentials are missing. 401 Unauthorized
Database Failure The database operation fails. 500 Internal Server Error
Unexpected Error An unhandled application problem occurs. 500 Internal Server Error

The status code should describe the actual failure. A missing resource is generally a 404 error, while unexpected server-side failures generally require a 500 response.

3. Diagram 1: How Error-Handling Middleware Works

The diagram below explains how a request can produce an error and how Express can pass that error to an error handler.

Client Request

Browser or API client sends a request

↓
Route Handler

Processes the request

↓
Error Occurs

An operation fails or detects a problem

↓
next(err)

Passes control to error-handling middleware

↓
Error-Handling Middleware

Logs the error and prepares a response

↓
Error Response

Client receives an appropriate status code

Step-by-step explanation:

  1. The client sends a request to the Express application.
  2. A route handler starts processing the request.
  3. An error occurs during the operation.
  4. The route passes the error using next(err), or a supported error-handling mechanism forwards it.
  5. Express skips regular middleware and looks for the next error handler.
  6. The error handler sends an appropriate response.
Important: Errors must be forwarded to Express to reach error-handling middleware. Errors thrown inside an asynchronous callback that Express does not automatically monitor must be caught and forwarded explicitly.

4. Creating Your First Error Handler

Let us create a simple application that deliberately forwards an error to the error-handling middleware.

Step 1: Create app.js

JavaScript
const express = require('express');

const app = express();

// Normal route
app.get('/', (req, res) => {
    res.send('Welcome to Express.js');
});

// Route that generates an error
app.get('/error', (req, res, next) => {
    const err = new Error('Something went wrong');
    next(err);
});

// Error-handling middleware
app.use((err, req, res, next) => {
    console.error(err.message);

    res.status(500).json({
        message: 'Internal Server Error'
    });
});

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

Step 2: Install Express.js

Terminal
npm init -y
npm install express

Step 3: Run the application

Terminal
node app.js

Step 4: Open the error URL

http://localhost:3000/error

Example terminal output:

Output
Server running on port 3000
Something went wrong

Browser JSON response:

JSON
{
    "message": "Internal Server Error"
}

The route calls next(err). Express forwards the error to the registered error handler, which logs the message and sends a JSON response with status code 500.

5. Handling a 404 Not Found Error

A 404 error means that the server could not find a matching resource or route. It is different from an unexpected server error, which is generally represented by status code 500.

A simple 404 handler can be registered after all application routes. It sends a response when no earlier route has handled the request.

JavaScript
const express = require('express');

const app = express();

app.get('/', (req, res) => {
    res.send('Home Page');
});

// 404 handler - register after routes
app.use((req, res) => {
    res.status(404).json({
        message: 'Route not found'
    });
});

// Error handler - register after the 404 handler
app.use((err, req, res, next) => {
    console.error(err.stack);

    res.status(500).json({
        message: 'Internal Server Error'
    });
});

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

Try this URL:

http://localhost:3000/unknown

Example response:

JSON
{
    "message": "Route not found"
}
Remember: In Express, a 404 response is usually handled by a regular middleware after the routes. It is not automatically treated as an error by Express.

6. Diagram 2: Difference Between 404 and 500 Errors

A missing route and an unexpected application error need different handling. The diagram illustrates the two common paths.

Incoming Request

Client requests a URL

↓
Route Processing

Express tries to process the request

No Matching Route

Request is not handled by a route

↓
404 Not Found

Regular 404 middleware responds

Application Error

Route forwards an error

↓
500 Internal Server Error

Error-handling middleware responds

Explanation:

  • 404: The requested route or resource was not found.
  • 500: An unexpected server-side error occurred.
  • The 404 handler usually sends a response without calling next().
  • The error handler receives errors forwarded through next(err) or supported error propagation.

7. Handling Errors in Asynchronous Code

Asynchronous operations, such as database queries or external API calls, may fail. Those errors must be forwarded to Express so that the error handler can process them.

The following example uses async and await. Express 5 automatically forwards rejected promises returned by route handlers. In Express 4, wrap the asynchronous logic in try...catch and call next(err).

JavaScript
const express = require('express');

const app = express();

app.get('/data', async (req, res, next) => {
    try {
        // Simulate a failed asynchronous operation
        throw new Error('Unable to load data');

    } catch (err) {
        next(err);
    }
});

app.use((err, req, res, next) => {
    console.error(err.message);

    res.status(500).json({
        message: 'Unable to process your request'
    });
});

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

Here, the error is caught and passed to next(err). The error-handling middleware then sends a safe response to the client.

Important: Do not expose database credentials, stack traces, secret keys, or internal system details in production error responses.

8. Best Practices for Error Handling

Practice Why It Matters
Register error handlers after routes Allows errors from earlier middleware and routes to reach the handler.
Use meaningful status codes Helps clients understand the kind of failure.
Log errors on the server Helps developers investigate and fix problems.
Send safe error messages Prevents exposing sensitive internal information.
Forward asynchronous errors Ensures failures reach Express error handling.
Avoid sending multiple responses Prevents response errors after headers have been sent.

Important Points to Remember

  • Error-handling middleware has four parameters: err, req, res, next.
  • Use next(err) to forward an error.
  • Register the error handler after the routes it should handle.
  • A 404 handler is generally regular middleware, not error-handling middleware.
  • Use 404 for missing routes and appropriate 500 responses for unexpected server failures.
  • Forward asynchronous errors to Express.
  • Never expose sensitive internal details to clients.
  • Do not send a second response after a response has already been sent.

Summary

Error-handling middleware provides a centralized way to handle application errors in Express.js. It receives the error, request, response, and next function, allowing the application to log failures and send suitable responses.

By forwarding errors correctly, distinguishing 404 responses from server errors, and keeping internal details private, developers can make Express.js applications easier to debug and more reliable.