Web Development chapters (5)
  1. 01HTML5 & Semantic Web Architecture
  2. 02CSS3 & Modern Styling Architecture
  3. 03Modern JavaScript (ES6+ & Asynchronous Engine)
  4. 04React.js Frontend Framework
  5. 05Backend Architecture with Node.js & Express

Chapter 05 · HTML, CSS, JS, React, Node

Backend Architecture with Node.js & Express

5 topics · 3 sections · beginner-friendly study notes · Updated

Share with friends:WhatsAppTelegram

Embed on your site

Free for teachers, schools and blogs. Please keep the attribution link.

Preview

Node.

js runs JavaScript on the server using V8 and the libuv event loop for non-blocking I/O. Core modules and streams handle files and network data efficiently, Express adds routing and middleware, REST principles shape clean APIs, and JWT with proper hashing secures them.

Full-stack interviews expect you to build and secure a simple REST API and explain middleware, streams and non-blocking I/O. REST/JSON backends for web and mobile apps, microservices, BFF layers, file processing and webhooks.

1

Node.js Architecture & Libuv

Node.js is a JavaScript runtime built on Chrome V8 (which compiles JS to machine code) with libuv providing the event loop, asynchronous I/O and a thread pool. JavaScript executes on a single thread; blocking operations are delegated to the OS (network) or to the libuv worker pool (file system, DNS lookup, crypto, zlib).

In short: One thread runs your code; slow I/O work is handed off and a callback runs when it finishes.

Think about it

Interviewers probe "Why is Node good for I/O but not for CPU-bound tasks?" and "Explain the event loop phases". A single waiter taking many orders: he never stands waiting at the kitchen, he hands in orders and serves whichever dish is ready.

The event loop has phases in order: timers (setTimeout/setInterval), pending callbacks, idle/prepare, poll (retrieve and run I/O callbacks), check (setImmediate), and close callbacks.

Between phases Node drains `process.

nextTick` first, then promise microtasks.

The libuv thread pool defaults to 4 threads (UV_THREADPOOL_SIZE).

Non-blocking I/O lets one process serve thousands of concurrent connections as long as handlers do not hog the loop with CPU-heavy work (JSON parsing of huge payloads, crypto in sync form, regex backtracking, big loops).

Use worker_threads for CPU work, the cluster module or process managers to use multiple cores, and queues or microservices for heavy jobs.

Modules: CommonJS (require) and ES modules (import, with "type": "module").

`package.

json` records dependencies and scripts.

Key points

  • V8: Google JavaScript engine that compiles JS to machine code.
  • libuv: C library providing the event loop, async I/O and thread pool.
  • Thread pool: Worker threads for fs, crypto, DNS and zlib operations (default 4).
  • process.nextTick: Callback queue processed before promise microtasks after the current operation.
  • Worker threads: Real threads for CPU-bound JavaScript work.

Example

Code
Event loop order, HTTP server and worker thread:
import http from "node:http";
import { Worker, isMainThread, parentPort, workerData } from "node:worker_threads";

setTimeout(() => console.log("timeout"), 0);
setImmediate(() => console.log("immediate"));
process.nextTick(() => console.log("nextTick"));
Promise.resolve().then(() => console.log("promise"));
// typical order: nextTick, promise, timeout/immediate (timeout vs immediate can vary at top level)

const server = http.createServer((req, res) => {
  if (req.url === "/time") {
    res.writeHead(200, { "Content-Type": "application/json" });
    return res.end(JSON.stringify({ now: new Date().toISOString() }));
  }
  res.writeHead(404).end("Not found");
});
server.listen(3000, () => console.log("listening on 3000"));

// CPU-heavy work off the main thread
if (isMainThread) {
  const w = new Worker(new URL(import.meta.url), { workerData: 40 });
  w.on("message", v => console.log("fib =", v));
} else {
  const fib = n => (n < 2 ? n : fib(n - 1) + fib(n - 2));
  parentPort.postMessage(fib(workerData));
}
2

Node Core Modules & Streams

Node ships built-in modules that need no installation: fs (files), path, os, http/https, crypto, events (EventEmitter), url, zlib, child_process, stream. Streams process data in chunks instead of loading it all in memory; the four types are Readable, Writable, Duplex and Transform.

In short: Streams move data piece by piece, like water through a pipe, so big files never fill memory.

Modules plug into your program

Think about it

Streams and the event-driven API are what make Node efficient for file, network and media workloads.

`fs.

readFile loads the entire file in memory - fine for small configs, dangerous for large files; fs.

createReadStream` reads in chunks (default 64 KB).

pipe() and `stream.

pipeline() connect streams and handle backpressure (a slow consumer signals the producer to pause); pipeline also forwards errors and cleans up, so prefer it over bare pipe`.

Use the promise APIs (`fs/promises, stream/promises`).

Avoid sync methods (readFileSync) inside request handlers because they block the event loop.

EventEmitter implements the observer pattern (on, once, emit); an unhandled error event crashes the process.

Always build file paths with `path.

join / path.

resolve` and validate user input to prevent path traversal (`..

/..

/etc/passwd`).

HTTP request and response objects are themselves streams.

Key points

  • Backpressure: Mechanism where a slow consumer tells a fast producer to pause.
  • Transform stream: Duplex stream that modifies data as it passes through (gzip, uppercase).
  • EventEmitter: Class implementing on/emit event handling.
  • Path traversal: Attack using ../ in file paths to access unintended files.

Example

Code
Streams with pipeline, Transform and EventEmitter:
import { createReadStream, createWriteStream } from "node:fs";
import { readFile, writeFile } from "node:fs/promises";
import { pipeline } from "node:stream/promises";
import { createGzip } from "node:zlib";
import { Transform } from "node:stream";
import { EventEmitter } from "node:events";
import path from "node:path";

// small file: read all at once
const cfg = JSON.parse(await readFile(path.join(process.cwd(), "config.json"), "utf8"));

// large file: stream + gzip with backpressure and error handling
await pipeline(
  createReadStream("big.log"),
  createGzip(),
  createWriteStream("big.log.gz")
);

// custom Transform
const upper = new Transform({
  transform(chunk, enc, cb) { cb(null, chunk.toString().toUpperCase()); },
});
await pipeline(process.stdin, upper, process.stdout);

// EventEmitter
const bus = new EventEmitter();
bus.on("order", o => console.log("received", o.id));
bus.emit("order", { id: 1 });

// safe file serving: block ../ traversal
function safePath(root, userPath) {
  const full = path.resolve(root, "." + path.sep + userPath);
  if (!full.startsWith(path.resolve(root) + path.sep)) throw new Error("Forbidden");
  return full;
}
3

Express Middleware & Routing

Express is a minimal web framework. A route maps an HTTP method and path to a handler (req, res). Middleware are functions (req, res, next) executed in order; each can modify req/res, end the response, or call next() (or next(err)) to continue. Error-handling middleware has four parameters (err, req, res, next) and is registered last.

In short: A request flows through a pipeline of functions until one sends a response.

Message hops across network

Think about it

Middleware order and error handling are the most-asked Express concepts.

Order matters

`express.

json() must run before routes that read req.

body`.

Route params (/users/:id), query strings (`req.

query) and bodies (req.

body`) carry input.

Use `express.

Router()` to modularise and mount under prefixes.

Route-level middleware (`app.

get("/me", requireAuth, handler)) applies to selected routes; app.

use` applies to all later routes.

A handler must either send a response or call next() - otherwise the request hangs; sending twice causes "headers already sent".

Async errors: in Express 4 pass them with next(err) or wrap handlers; Express 5 forwards rejected promises automatically.

A 404 handler goes after all routes and the error handler last.

Common middleware: `cors, helmet` (security headers), morgan (logging), compression, express-rate-limit, cookie-parser.

Separate concerns into routes, controllers and services.

Key points

  • Middleware: Function in the request pipeline with access to req, res and next.
  • Router: Mini-app for grouping routes under a prefix.
  • req.params / query / body: Path variables, URL query string, parsed request payload.
  • next(err): Skips to the error-handling middleware.

Example

Code
Express app with middleware chain and routers:
import express from "express";
import helmet from "helmet";
import cors from "cors";

const app = express();
app.use(helmet());
app.use(cors({ origin: "https://myapp.com" }));
app.use(express.json({ limit: "100kb" }));          // parse JSON bodies BEFORE routes
app.use((req, res, next) => {                        // logger middleware
  const start = Date.now();
  res.on("finish", () => console.log(req.method, req.originalUrl, res.statusCode, Date.now() - start + "ms"));
  next();
});

const router = express.Router();
router.get("/:id", async (req, res, next) => {
  try {
    const user = await db.users.find(req.params.id);
    if (!user) return res.status(404).json({ error: "User not found" });
    res.json(user);
  } catch (err) { next(err); }
});
app.use("/api/users", router);

app.get("/health", (req, res) => res.json({ ok: true }));

// 404 handler (after all routes)
app.use((req, res) => res.status(404).json({ error: "Not found" }));

// error handler (4 args, registered last)
app.use((err, req, res, next) => {
  console.error(err);
  res.status(err.status || 500).json({ error: process.env.NODE_ENV === "production" ? "Internal error" : err.message });
});

app.listen(process.env.PORT || 3000);
4

RESTful API Architecture

REST models server data as resources identified by URLs and manipulated with standard HTTP methods: GET (read), POST (create), PUT (replace), PATCH (partial update), DELETE (remove). Constraints include client-server, statelessness, cacheability, a uniform interface and a layered system. Responses use proper status codes and consistent JSON.

In short: Nouns in URLs, verbs in HTTP methods, meaningful status codes.

Browser request flow

Think about it

Designing endpoints and choosing status codes is a standard backend interview task.

Use plural nouns (/users, /users/42, /users/42/orders).

Status codes: 200 OK, 201 Created (+ Location), 204 No Content, 400 Bad Request (malformed), 401 Unauthorized (not authenticated), 403 Forbidden (authenticated but not allowed), 404 Not Found, 409 Conflict, 422 Unprocessable Entity (validation), 429 Too Many Requests, 500 Internal Server Error.

GET, PUT and DELETE are idempotent; POST is not; GET and HEAD are safe (no side effects).

PATCH is usually not guaranteed idempotent.

Support pagination (`?

page=2&limit=20 or cursors), filtering, sorting, and a consistent error shape ({ error: { code, message, details } }`).

Version the API (/v1).

Statelessness means each request carries everything needed (e.

g.

a token), enabling horizontal scaling behind a load balancer.

Cache with ETag and Cache-Control.

Validate input with a schema (zod, joi) and never expose internal errors or stack traces.

Key points

  • Idempotent: Repeating the request yields the same server state.
  • Safe method: Does not modify server state (GET, HEAD).
  • Stateless: Server stores no client session between requests.
  • HATEOAS: Responses include links to related actions (rarely fully implemented).

Example

Code
CRUD REST endpoints with pagination:
const users = [];
let nextId = 1;

// GET /users?page=1&limit=10
app.get("/users", (req, res) => {
  const page = Math.max(1, Number(req.query.page) || 1);
  const limit = Math.min(100, Number(req.query.limit) || 10);
  const start = (page - 1) * limit;
  res.json({ data: users.slice(start, start + limit), page, limit, total: users.length });
});

app.get("/users/:id", (req, res) => {
  const u = users.find(x => x.id === Number(req.params.id));
  if (!u) return res.status(404).json({ error: "User not found" });
  res.json(u);
});

app.post("/users", (req, res) => {
  const { name, email } = req.body;
  if (!name || !email) return res.status(400).json({ error: "name and email required" });
  if (users.some(u => u.email === email)) return res.status(409).json({ error: "Email already exists" });
  const user = { id: nextId++, name, email };
  users.push(user);
  res.status(201).location("/users/" + user.id).json(user);
});

app.patch("/users/:id", (req, res) => {
  const u = users.find(x => x.id === Number(req.params.id));
  if (!u) return res.status(404).end();
  Object.assign(u, req.body);
  res.json(u);
});

app.delete("/users/:id", (req, res) => {
  const i = users.findIndex(x => x.id === Number(req.params.id));
  if (i === -1) return res.status(404).end();
  users.splice(i, 1);
  res.status(204).end();
});
5

JWT Authentication & Security

Authentication verifies who the user is; authorization decides what they may do. A JSON Web Token (JWT) is a signed token header.payload.signature that carries claims (sub, exp, role). The server signs it with a secret or private key and verifies it on each request, so no server-side session is required. Passwords must be stored as salted slow hashes (bcrypt, argon2), never in plain text.

In short: Check identity once, hand out a signed pass, and verify the pass on later requests.

Think about it

Authentication questions test security awareness: hashing, tokens, cookies, XSS/CSRF and common OWASP risks.

Flow

user posts credentials -> server compares with `bcrypt.

compare` -> issues a short-lived access token (e.

g.

15 min) and a longer refresh token -> client sends Authorization: Bearer <token> -> auth middleware verifies the signature and expiry and attaches `req.

user`.

A JWT is signed (tamper-evident) but not encrypted: anyone can read the payload, so never put secrets in it.

Always verify with a fixed algorithm and check exp; never accept alg: none.

Storage: HttpOnly + Secure + SameSite cookies protect tokens from XSS theft (but need CSRF defences); localStorage is exposed to XSS.

JWTs cannot be revoked easily - use short expiry, refresh-token rotation or a deny-list.

Authorization: role/permission checks in middleware (requireRole("admin")).

Other protections: HTTPS everywhere, helmet, CORS allow-list, rate limiting on login, input validation, parameterised queries (SQL injection), output escaping (XSS), secrets in environment variables (never in git), generic login errors ("Invalid credentials"), 401 = not authenticated and 403 = forbidden.

Key points

  • Salt: Random value added before hashing so identical passwords hash differently.
  • JWT: Signed token with claims; verified using a secret or public key.
  • Refresh token: Long-lived credential used to get new short-lived access tokens.
  • CSRF: Attack abusing cookie-based sessions; mitigated by SameSite and tokens.
  • RBAC: Role-based access control for authorization.

Read more

Example

Code
bcrypt, JWT, cookies, RBAC and rate limiting:
import bcrypt from "bcrypt";
import jwt from "jsonwebtoken";
import rateLimit from "express-rate-limit";

const loginLimiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 10 });

app.post("/register", async (req, res) => {
  const hash = await bcrypt.hash(req.body.password, 12);   // salted, slow
  // save { email, passwordHash: hash, role: "user" } to DB
  res.status(201).json({ ok: true });
});

app.post("/login", loginLimiter, async (req, res) => {
  const user = await findUserByEmail(req.body.email);
  const ok = user && (await bcrypt.compare(req.body.password, user.passwordHash));
  if (!ok) return res.status(401).json({ error: "Invalid credentials" });   // generic message
  const token = jwt.sign({ sub: user.id, role: user.role }, process.env.JWT_SECRET, {
    expiresIn: "15m", algorithm: "HS256",
  });
  res.cookie("token", token, { httpOnly: true, secure: true, sameSite: "strict", maxAge: 15 * 60 * 1000 });
  res.json({ ok: true });
});

function requireAuth(req, res, next) {
  const header = req.headers.authorization || "";
  const token = header.startsWith("Bearer ") ? header.slice(7) : req.cookies?.token;
  if (!token) return res.status(401).json({ error: "Unauthorized" });
  try {
    req.user = jwt.verify(token, process.env.JWT_SECRET, { algorithms: ["HS256"] });
    next();
  } catch {
    res.status(401).json({ error: "Invalid or expired token" });
  }
}

const requireRole = role => (req, res, next) =>
  req.user?.role === role ? next() : res.status(403).json({ error: "Forbidden" });

app.get("/me", requireAuth, (req, res) => res.json({ id: req.user.sub }));
app.delete("/admin/users/:id", requireAuth, requireRole("admin"), (req, res) => res.status(204).end());

// config: secrets come from the environment, fail fast when missing
if (!process.env.JWT_SECRET) throw new Error("Missing JWT_SECRET");

Solved examples

Example 01 · Basic

Create an Express server with GET /hello returning { message: "Hi" } on port 3000.

Given Data:
    Required To Find:

    Code

    Formula Applied:—
    Step-by-Step Solution:
    Step 1: Import and create app
    Step 2: Define app.get("/hello", handler)
    Step 3: Call res.json
    Step 4: app.listen(3000)
    Final Answer: import express from "express"; const app = express(); app.get("/hello", (req, res) => res.json({ message: "Hi" })); app.listen(3000);

    Approach note: res.json sets Content-Type and serialises for you.

    Example 02 · Intermediate

    Why does req.body come out undefined in a POST /users handler, and how do you fix it?

    Given Data:
      Required To Find:

      Cause and fix

      Formula Applied:—
      Step-by-Step Solution:
      Step 1: Express does not parse bodies by default
      Step 2: Register app.use(express.json()) before the routes
      Step 3: Client must send Content-Type: application/json
      Final Answer: The body parser middleware is missing or registered after the route; add app.use(express.json()) before routes.

      Approach note: Middleware executes in registration order.

      Example 03 · Advanced

      Choose status codes: (a) created a user, (b) missing JWT, (c) valid JWT but not admin, (d) duplicate email.

      Given Data:
        Required To Find:

        Codes

        Formula Applied:—
        Step-by-Step Solution:
        Step 1: Creation -> 201
        Step 2: Unauthenticated -> 401
        Step 3: Authenticated but forbidden -> 403
        Step 4: Conflict with existing resource -> 409
        Final Answer: (a) 201, (b) 401, (c) 403, (d) 409

        Approach note: 401 = who are you? 403 = I know you, but no.

        Example 04 · Intermediate

        Serve a 2 GB log file download from Express without exhausting memory.

        Given Data:
          Required To Find:

          Approach and code

          Formula Applied:—
          Step-by-Step Solution:
          Step 1: Do not use readFile - it loads all 2 GB into memory
          Step 2: Create a read stream of the file
          Step 3: Use pipeline to send it to the response with backpressure and error handling
          Step 4: Set Content-Type / Content-Disposition headers first
          Final Answer: app.get("/logs", (req, res, next) => { res.setHeader("Content-Type", "text/plain"); pipeline(createReadStream("big.log"), res, err => err && next(err)); });

          Approach note: Streams keep memory flat regardless of file size.

          Example 05 · Advanced

          A route computes a heavy fibonacci(45) and every other request becomes slow while it runs. Why, and what are the options?

          Given Data:
            Required To Find:

            Explanation and fixes

            Formula Applied:—
            Step-by-Step Solution:
            Step 1: The computation is synchronous CPU work on the single JS thread, so the event loop cannot process other callbacks
            Step 2: Move it to a worker_thread (or a separate service/queue)
            Step 3: Alternatively cache results or use an iterative algorithm
            Step 4: Scale across cores with the cluster module or multiple processes
            Final Answer: It blocks the event loop; offload CPU-bound work to worker threads or a job queue and keep handlers non-blocking.

            Approach note: Node excels at I/O concurrency, not CPU parallelism, unless workers are used.

            Example 06 · Advanced

            Write Express middleware that allows only users with the "admin" role after JWT authentication.

            Given Data:
              Required To Find:

              Middleware

              Formula Applied:—
              Step-by-Step Solution:
              Step 1: First run requireAuth which sets req.user from the verified JWT
              Step 2: Create a requireRole(role) factory returning middleware
              Step 3: If req.user.role matches call next(); else respond 403
              Step 4: Chain: app.delete(path, requireAuth, requireRole("admin"), handler)
              Final Answer: const requireRole = role => (req, res, next) => req.user?.role === role ? next() : res.status(403).json({ error: "Forbidden" });

              Approach note: Authenticate first (401), then authorise (403).

              Real-world applications

              Web

              Using Backend Architecture with Node.js & Express in real projects

              REST/JSON backends for web and mobile apps, microservices, BFF layers, file processing and webhooks.

              Mechanism: Write small programs, read errors carefully, then grow complexity only after the basics are solid.

              Common mistakes

              ❌ Myth: Node.js is multi-threaded so it is great for heavy computation.

              Why this is wrong: JavaScript runs on one thread; CPU-heavy work blocks the event loop and stalls every request.

              ✅ Verified Truth: Offload to worker threads, queues or other services.

              ⚠️ Exam Tip: Say "good for I/O-bound, not CPU-bound".

              ❌ Myth: JWT payloads are encrypted.

              Why this is wrong: They are only base64url-encoded and signed.

              ✅ Verified Truth: Anyone can read the claims; never include secrets.

              ⚠️ Exam Tip: Distinguish signing from encryption.

              ❌ Myth: Hashing passwords with SHA-256 is enough.

              Why this is wrong: Fast hashes are easy to brute-force.

              ✅ Verified Truth: Use slow, salted algorithms such as bcrypt or argon2.

              ⚠️ Exam Tip: Mention salt and work factor.

              ❌ Myth: readFile is fine for any file size.

              Why this is wrong: It buffers the whole file in memory and can crash the process for large files.

              ✅ Verified Truth: Use streams with pipeline for large data.

              ⚠️ Exam Tip: Mention backpressure.

              ❌ Myth: Middleware order does not matter in Express.

              Why this is wrong: Handlers run in registration order; body parsers, auth and error handlers must be placed correctly.

              ✅ Verified Truth: Register parsers and security middleware first, routes next, 404 and the error handler last.

              ⚠️ Exam Tip: Use the req.body undefined example.

              ❌ Myth: A JWT can simply be deleted on the server to log a user out.

              Why this is wrong: Stateless JWTs are valid until they expire; the server has no session to delete.

              ✅ Verified Truth: Use short lifetimes, refresh-token rotation or a deny-list.

              ⚠️ Exam Tip: Explain the revocation trade-off.

              Revision notes

              Node.js runs JavaScript on the server using V8 and the libuv event loop for non-blocking I/O. Core modules and streams handle files and network data efficiently, Express adds routing and middleware, REST principles shape clean APIs, and JWT with proper hashing secures them.

              High-Yield Quick Revision Points

              1. Node = V8 + libuv; single JS thread with event loop phases; thread pool for fs/crypto/dns
              2. avoid blocking the loop; worker_threads / cluster / queues for CPU work
              3. streams + pipeline = constant memory, backpressure, error handling
              4. build paths with path.join and block ../ traversal
              5. middleware (req,res,next) runs in order; parsers first, error handler (4 args) last
              6. GET/POST/PUT/PATCH/DELETE semantics; idempotent and safe methods
              7. 200/201/204/400/401/403/404/409/422/429/500
              8. plural nouns, pagination, consistent error JSON, versioning
              9. bcrypt (salted, slow) + JWT (signed, not encrypted), short expiry, refresh tokens
              10. HttpOnly Secure SameSite cookies, rate limiting, validation, helmet, CORS allow-list
              11. secrets in env, never in git

              Practice questions

              Question 1 · MCQ (Interview / semester)

              Which middleware signature handles errors in Express?

              Question 2 · MCQ (Interview / semester)

              Which HTTP status indicates successful resource creation?

              Question 3 · MCQ (Interview / semester)

              Where should the database password be stored?

              Question 4 · MCQ (Interview / semester)

              Which HTTP method is idempotent?

              Question 5 · MCQ (Interview / semester)

              Which library provides Node event loop and async I/O?

              Question 6 · MCQ (Interview / semester)

              What does a stream pipeline handle that a plain pipe may not?

              Question 7 · MCQ (Interview / semester)

              Which task runs on the libuv thread pool?

              Question 8 · MCQ (Interview / semester)

              A request has a valid token but the user lacks permission. Which status?

              Question 9 · MCQ (Interview / semester)

              Which part of a JWT proves it was not tampered with?

              Question 10 · MCQ (Interview / semester)

              Which cookie flags help protect a session token?