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

Authorization and Protected Routes in Node.js

Authorization determines what an authenticated user is allowed to do. In Node.js applications, authorization is commonly implemented using middleware, roles, permissions, and protected API routes.

1. What Is Authorization?

Authorization is the process of deciding whether a user has permission to access a particular resource or perform a specific action.

For example, an Admin may manage all users, while a normal User may only view their own profile.

Concept Meaning Example
Authentication Verifies who the user is. Checking email and password during login.
Authorization Checks what the user can access. Allowing only Admins to delete users.
Easy trick: Authentication = Who are you? Authorization = What are you allowed to do?

2. Why Do We Need Authorization?

  • To prevent unauthorized access to sensitive resources.
  • To restrict administrative operations to approved users.
  • To protect user-specific information.
  • To enforce business rules and permissions.
  • To separate access for Admin, Manager, and User roles.

3. How Authorization Works

Step 1: User Sends a Request

The client requests a protected API.

↓
Step 2: Authentication

JWT middleware verifies the user's token.

↓
Step 3: Authorization

The server checks the user's role or permission.

↓
Step 4: Access Decision

The request is allowed or rejected.

4. What Is Role-Based Authorization?

Role-Based Access Control (RBAC) assigns permissions according to a user's role. The application checks the role before allowing a restricted operation.

Role View Profile Manage Users Delete Users
Admin Yes Yes Yes
Manager Yes Limited No
User Own profile No No

The table is an example policy. Actual permissions depend on your application's business requirements.

5. Use the JWT Authentication Middleware

In the previous lesson, we created authenticateToken. It verifies the JWT and adds the verified user ID to req.user. Authorization middleware can run after that check.

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;
Important: A verified JWT proves that the token is valid under your verification rules. It does not automatically mean that the user is an Admin.

6. Create Role-Based Authorization Middleware

Create a middleware that checks whether the authenticated user has an allowed role.

JavaScript — roleMiddleware.js
function authorizeRoles(...allowedRoles) {
    return (req, res, next) => {
        if (!req.user || !allowedRoles.includes(req.user.role)) {
            return res.status(403).json({
                message: "You do not have permission to access this resource."
            });
        }

        next();
    };
}

module.exports = authorizeRoles;

This middleware expects req.user.role to be populated from a trusted source before it runs. We will load the current user's role from the database in the next example.

7. Load the User Role from the Database

For sensitive operations, load the user's current role from the database after verifying the token. This means a role change in the database can take effect without trusting a role supplied by the client.

JavaScript — loadUserRole.js
const db = require("./db");

async function loadUserRole(req, res, next) {
    try {
        const [users] = await db.execute(
            "SELECT id, role FROM users WHERE id = ?",
            [req.user.id]
        );

        if (users.length === 0) {
            return res.status(401).json({
                message: "User account not found."
            });
        }

        req.user.role = users[0].role;

        next();
    } catch (error) {
        console.error("Role lookup error:", error);

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

module.exports = loadUserRole;
Database requirement: This example assumes your users table contains a role column. Add it through a proper database migration if it does not exist. Assign roles only through trusted, access-controlled server operations.

8. Create Protected Routes

We can now combine authentication, role loading, and authorization to protect an Admin-only endpoint.

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

const express = require("express");
const authenticateToken = require("./authMiddleware");
const loadUserRole = require("./loadUserRole");
const authorizeRoles = require("./roleMiddleware");

const app = express();

app.use(express.json());

// Any authenticated user can access this route.
app.get("/api/profile", authenticateToken, (req, res) => {
    res.status(200).json({
        message: "Profile endpoint accessed successfully.",
        userId: req.user.id
    });
});

// Only Admin users can access this route.
app.get(
    "/api/admin/users",
    authenticateToken,
    loadUserRole,
    authorizeRoles("Admin"),
    (req, res) => {
        res.status(200).json({
            message: "Admin access granted."
        });
    }
);

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

app.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`);
});

Middleware runs in order. First, the JWT is verified. Next, the user's current role is loaded. Finally, the role is checked before the endpoint runs.

9. Test Authorization in Postman

Test 1: Access the Profile

HTTP Request
GET http://localhost:3000/api/profile

Add a valid JWT in Authorization → Bearer Token. An authenticated user should receive a successful response.

Test 2: Access the Admin Route as Admin

HTTP Request
GET http://localhost:3000/api/admin/users

Expected response for a user whose database role is Admin:

JSON
{
    "message": "Admin access granted."
}

Test 3: Access the Admin Route as a Normal User

Send the same request using a valid token for a user whose database role is User.

JSON — Expected Response
{
    "message": "You do not have permission to access this resource."
}

The server returns 403 Forbidden because the user is authenticated but does not have the required role.

10. Authentication vs Authorization Status Codes

Status Code Meaning
200 OK The request succeeded.
401 Unauthorized The request has missing or invalid authentication.
403 Forbidden The user is authenticated but lacks permission.
500 Internal Server Error An unexpected server-side error occurred.

11. Authorization Best Practices

  • Verify authentication before checking permissions.
  • Never trust a role sent directly by the client.
  • Use the database or another trusted source for sensitive permissions.
  • Apply authorization checks to every protected endpoint.
  • Restrict users to their own records unless they have broader permission.
  • Use the principle of least privilege.
  • Return 401 for authentication failures and 403 for insufficient permissions.
  • Test both allowed and denied access scenarios.

Important Points to Remember

  • Authentication verifies the user's identity.
  • Authorization checks the user's permissions.
  • Role-based authorization is commonly called RBAC.
  • Authentication middleware can populate req.user.
  • Authorization middleware checks roles or permissions.
  • Use 401 for invalid authentication and 403 for denied access.
  • Never allow users to assign themselves privileged roles.

Summary

Authorization controls which actions an authenticated user can perform. By combining JWT authentication, trusted role lookup, and role-based middleware, a Node.js application can protect sensitive APIs and restrict access according to business requirements.