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

JWT Authentication in Node.js

JWT (JSON Web Token) is a way to securely transmit verified information between a client and a server. In Node.js applications, JWT is commonly used to authenticate users and protect API endpoints.

1. What Is JWT?

JWT stands for JSON Web Token. After a user successfully logs in, the server can generate a signed token and send it to the client. The client then sends this token with requests to protected APIs.

A JWT commonly contains three parts:

Part Purpose
Header Identifies the token type and signing algorithm.
Payload Contains claims such as the user's ID and token expiry.
Signature Allows the server to verify that the token has not been modified.
Important: A signed JWT is not automatically encrypted. Do not store passwords, database credentials, or other sensitive information in its payload.

2. Why Do We Use JWT?

  • To authenticate users after login.
  • To protect APIs from unauthenticated requests.
  • To identify the user making a request.
  • To validate a token's signature and expiration.
  • To avoid requiring a traditional server-side session for every API request.
Remember: Authentication checks who the user is. Authorization checks what the user is allowed to do.

3. Install Required Packages

Open your terminal in the Node.js project folder and run:

Terminal
npm install express bcrypt jsonwebtoken mysql2 dotenv

These packages are used for the following purposes:

Package Purpose
express Creates API routes and middleware.
bcrypt Compares the submitted password with its stored hash.
jsonwebtoken Creates and verifies JWT tokens.
mysql2 Connects to the MySQL database.
dotenv Loads configuration values from the .env file.

4. Configure the JWT Secret

Create a .env file in the project root. Keep the signing secret private and never commit it to source control.

.env
JWT_SECRET=replace_with_a_strong_random_secret
JWT_ISSUER=node-auth-demo
JWT_AUDIENCE=node-auth-api

Generate a strong random secret using Node.js:

Terminal
node -e "console.log(require('crypto').randomBytes(64).toString('hex'))"

Replace the placeholder with the generated value. Add .env to .gitignore so the secret is not committed.

5. How JWT Authentication Works

Step 1: User Login

The user submits an email and password.

↓
Step 2: Verify Credentials

The server checks the user record and password hash.

↓
Step 3: Generate JWT

The server signs a token and returns it to the client.

↓
Step 4: Send the Token

The client sends the token in the Authorization header.

↓
Step 5: Verify and Access

The server verifies the token before returning protected data.

6. Generate a JWT After Login

In the previous User Login page, we checked the user's email and password. Now we will update that login endpoint so a successful login also returns a JWT.

JavaScript — authRoutes.js
const express = require("express");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const db = require("./db");

const router = express.Router();

router.post("/login", async (req, res) => {
    try {
        const { email, password } = req.body;

        if (
            typeof email !== "string" ||
            typeof password !== "string" ||
            !email.trim() ||
            !password
        ) {
            return res.status(400).json({
                message: "Email and password are required."
            });
        }

        const [users] = await db.execute(
            "SELECT id, name, email, password_hash FROM users WHERE email = ?",
            [email.trim()]
        );

        if (users.length === 0) {
            return res.status(401).json({
                message: "Invalid email or password."
            });
        }

        const user = users[0];

        const passwordMatches = await bcrypt.compare(
            password,
            user.password_hash
        );

        if (!passwordMatches) {
            return res.status(401).json({
                message: "Invalid email or password."
            });
        }

        if (!process.env.JWT_SECRET) {
            throw new Error("JWT_SECRET is not configured.");
        }

        const token = jwt.sign(
            { sub: String(user.id) },
            process.env.JWT_SECRET,
            {
                expiresIn: "15m",
                issuer: process.env.JWT_ISSUER,
                audience: process.env.JWT_AUDIENCE
            }
        );

        return res.status(200).json({
            message: "Login successful.",
            token,
            tokenType: "Bearer",
            expiresIn: 900,
            user: {
                id: user.id,
                name: user.name,
                email: user.email
            }
        });
    } catch (error) {
        console.error("Login error:", error);

        return res.status(500).json({
            message: "An internal server error occurred."
        });
    }
});

module.exports = router;
Note: This example assumes the users table has id, name, email, and password_hash columns. Match these names to your actual schema.

The sub claim identifies the user. The token expires after 15 minutes, so the client must sign in again or use a separately implemented refresh-token flow when it expires.

7. Create JWT Authentication Middleware

Middleware runs before a protected route. It checks whether the request contains a valid Bearer token.

JavaScript — authMiddleware.js
const jwt = require("jsonwebtoken");

function authenticateToken(req, res, next) {
    const authorization = req.headers.authorization;

    if (!authorization || !authorization.startsWith("Bearer ")) {
        return res.status(401).json({
            message: "Authentication token is required."
        });
    }

    const token = authorization.slice(7).trim();

    if (!token) {
        return res.status(401).json({
            message: "Authentication token is required."
        });
    }

    try {
        const decoded = jwt.verify(
            token,
            process.env.JWT_SECRET,
            {
                issuer: process.env.JWT_ISSUER,
                audience: process.env.JWT_AUDIENCE,
                algorithms: ["HS256"]
            }
        );

        if (typeof decoded.sub !== "string") {
            return res.status(401).json({
                message: "Invalid authentication token."
            });
        }

        req.user = {
            id: decoded.sub
        };

        next();
    } catch (error) {
        return res.status(401).json({
            message: "Invalid or expired authentication token."
        });
    }
}

module.exports = authenticateToken;

jwt.verify() checks the token's signature, expiration, issuer, and audience. If verification fails, the request is rejected.

8. Protect an API Route

After creating the middleware, apply it to routes that require a logged-in user.

JavaScript — server.js
require("dotenv").config();

const express = require("express");
const authenticateToken = require("./authMiddleware");
const authRoutes = require("./authRoutes");

const app = express();

app.use(express.json());
app.use("/api/auth", authRoutes);

app.get("/api/auth/me", authenticateToken, (req, res) => {
    res.status(200).json({
        message: "Protected API accessed successfully.",
        userId: req.user.id
    });
});

const PORT = process.env.PORT || 3000;

app.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`);
});
Important: Load dotenv before using process.env. Keep your existing database setup in db.js and make sure the route file imports the correct pool.

9. Test JWT Authentication in Postman

Step 1: Login

Send a POST request to:

URL
http://localhost:3000/api/auth/login

Select Body → raw → JSON:

JSON
{
    "email": "user@example.com",
    "password": "YourPasswordHere"
}

After a successful login, copy the token value from the response.

Step 2: Call the Protected API

Send a GET request to:

URL
http://localhost:3000/api/auth/me

In Postman, open the Authorization tab, select Bearer Token, and paste the token.

Expected Successful Response

JSON
{
    "message": "Protected API accessed successfully.",
    "userId": "1"
}

The user ID shown here is only an example. Your response will contain the ID represented by the verified token.

10. Common HTTP Status Codes

Status Code Meaning
200 OK Login or protected request succeeded.
400 Bad Request Required login information is missing or invalid.
401 Unauthorized Credentials or token are invalid, missing, or expired.
403 Forbidden The user is authenticated but lacks permission for an action.
500 Internal Server Error An unexpected server-side error occurred.

11. JWT Security Best Practices

  • Use a strong, private signing secret and rotate it when necessary.
  • Use HTTPS in production.
  • Set a reasonable token expiration time.
  • Never include passwords or other secrets in the token payload.
  • Validate the token's signature, issuer, audience, and expiration.
  • Apply login rate limiting and input validation.
  • Do not assume a valid token automatically grants administrator permissions.
  • For browser applications, carefully evaluate secure HttpOnly cookies with appropriate SameSite settings. Protect cookie-based requests against CSRF.
  • Remember that a JWT normally remains usable until expiry unless you implement revocation or another invalidation strategy.

Important Points to Remember

  • JWT stands for JSON Web Token.
  • jwt.sign() creates a signed token.
  • jwt.verify() verifies the token.
  • The client sends the token using the Bearer authorization scheme.
  • Authentication middleware protects API endpoints.
  • A signed JWT is not the same as an encrypted JWT.
  • Authorization rules must be implemented separately.

Summary

JWT authentication allows a Node.js server to issue a signed token after successful login and verify it on later requests. By combining jsonwebtoken, authentication middleware, token expiry, and secure secret management, you can protect APIs from unauthenticated access. In the next lesson, we will learn Authorization and Protected Routes.