Module 0

HTTP & Web Foundations

How the Web Works β€’ Requests & Responses β€’ Status Codes

🌐 How the Web Works

Before writing JavaScript, you need to understand the protocol that powers the web. Every time you visit a website, your browser speaks HTTP β€” a simple language of requests and responses.

This module covers the fundamentals of HTTP: how clients talk to servers, what happens inside each message, and the status codes and headers that control everything from caching to authentication.

🎯 By the end of this module, you will:

  • Understand the client-server model and how HTTP requests flow
  • Read and interpret HTTP messages (start line, headers, body)
  • Use status codes correctly (2xx, 3xx, 4xx, 5xx)
  • Know key HTTP headers and their purpose
  • See how JavaScript runs in browsers and on the server (Node.js)
🌐HTTP Protocol
  • Client-server architecture
  • Request/response cycle
  • Status codes & headers
⚑JavaScript Core
  • Functions, objects & arrays
  • Async: Promises & async/await
  • Modern ES6+ syntax
πŸ–₯️Browser APIs
  • DOM manipulation
  • Events & event handling
  • Fetch API & AJAX
πŸš€Node.js
  • Server-side JavaScript
  • File system & modules
  • Building APIs

πŸ“š Course Flow

HTTP Basics β†’ JS Core β†’ Browser β†’ Node.js

πŸ”€ HTTP Topology: The Big Picture

Below is a live topology of how HTTP works. Multiple clients (browser, mobile, CLI) send requests to the server, and the server can call external APIs too. Click Play to watch the flow.

πŸ‘₯ Client & Server: How They Connect

Every HTTP request involves a client and a server.

πŸ”„ Roles per request

A client starts a request; a server answers. In chains (your server β†’ external API) the roles switch per hop.

πŸ”Œ Why ports?

One IP, many apps. The OS delivers packets to the process bound to the destination port (e.g. 80, 443, 3000).

🌍 DNS β†’ IP

Resolve example.com to an IP address (cached by TTL). CDNs often answer with a nearby edge server.

🀝 Connect, then HTTP

TCP 3‑way handshake β†’ TLS (for HTTPS) β†’ send request line + headers β†’ receive response.

πŸ”Œ Deep Dive: Ports & Sockets

πŸ”Œ Overview

  • Well‑known vs dynamic: 80/443 (HTTP/HTTPS), 22 (SSH), 25 (SMTP), 5432 (Postgres). Clients pick an ephemeral source port per connection.
  • One IP, many services: Ports let multiple protocols coexist (web, SSH, mail) on a single interface.
  • 4‑tuple identity: A TCP connection = (srcIP:srcPort ⇄ dstIP:dstPort). This uniquely identifies the conversation.

πŸ”„ Lifecycle

  • bind: Process requests a local ip:port.
  • listen: Kernel queues SYNs on the listening socket.
  • accept: Each accepted connection spawns a new socket (same local port, new remote 4‑tuple).
  • TIME_WAIT: After close, socket stays around briefly to catch late packets.

πŸ”’ Security

  • Firewalls: Rules frequently target destination ports (e.g. allow 443, deny 23).
  • Least privilege: Services under 1024 often started via a helper (systemd socket activation, reverse proxy).
  • Scanning: Port scans reveal attack surface; rate limiting + stealth ports reduce noise.

🌐 Virtual & Proxy Layers

  • Virtual hosting: Same 443 handles many domains via HTTP Host + TLS SNI.
  • Reverse proxy: Edge (443) fans into internal ports (e.g. 3000 API, 3100 auth, 3200 assets).
  • Containers: Host port 8080 β†’ container 127.0.0.1:80; kube‑services abstract pods behind stable ports.

🎲 Ephemeral Ports

  • Range: Often 49152–65535 (Linux configurable via /proc/sys/net/ipv4/ip_local_port_range).
  • Selection: Kernel chooses a free port; randomness defends against spoofing.
  • Observation: Seeing many adjacent source ports can indicate sequential allocation (old OS behavior).
Terminal
lsof -iTCP -sTCP:LISTEN -n | grep -E ':(80|443|3000)'  # Show listening sockets
ss -tulpn                                                   # Modern socket summary
netstat -an | grep 443                                      # Legacy netstat usage
iptables -L -n | grep 443                                   # Firewall rule referencing a port
sysctl net.ipv4.ip_local_port_range                         # Ephemeral range
🌍 Deep Dive: DNS Resolution

Core Flow

  1. App asks OS stub resolver.
  2. Stub queries recursive (e.g. 1.1.1.1).
  3. Recursive walks: root β†’ TLD (.com) β†’ authoritative (zone NS).
  4. Answer cached at each layer until TTL expires.

πŸ“‹ Record Types

  • A / AAAA: IPv4 / IPv6 address.
  • CNAME: Alias chain (never with other data at same node).
  • MX: Mail exchangers (with priority numbers).
  • TXT: Arbitrary text (SPF, domain verification).
  • SRV: Service discovery (host + port + priority/weight).
  • CAA: Restrict which CAs can issue certificates.
  • NS: Delegation points for subzones.

⏱️ Caching & TTL

  • Layered: Browser β†’ OS β†’ recursive β†’ authoritative.
  • Negative: NXDOMAIN cached per SOA MINIMUM or explicit TTL.
  • Tuning: Low TTL for active failover; higher TTL for stability/perf.

πŸ—ΊοΈ Geo & CDN

  • Anycast resolvers: One IP, many edge POPs.
  • Latency steering: Different A answers per region.
  • Health checks: Remove bad endpoints before clients see them.

πŸ” Security

  • DNSSEC: Signatures prove authenticity (no privacy).
  • DoT / DoH: Encrypt resolver channel; hides queries from local network.
  • Mitigations: Random source port + query ID thwart basic spoofing.
Terminal
dig +trace example.com                 # Full resolution path
dig A example.com @1.1.1.1             # Force specific resolver
dig CAA example.com                    # Certificate authority authorization
dig _sip._tcp.example.com SRV          # Service record lookup
drill -S example.com                   # DNSSEC validation with drill
nslookup -type=MX example.com
🀝 Deep Dive: Connect, then HTTP

Handshake Stack

  1. TCP: SYN β†’ SYN‑ACK β†’ ACK establishes reliability metadata (seq/ack windows).
  2. TLS: ClientHello (SNI, ALPN, cipher suites) β†’ ServerHello (chosen params, cert) β†’ key exchange β†’ Finished.
  3. HTTP framing: Request line + headers (or HTTP/2 binary frames / HTTP/3 QUIC frames).

1️⃣ HTTP/1.1

  • Textual, one request at a time per connection (pipeline risks HOL blocking).
  • Upgrade: Connection: keep-alive reduces extra handshakes.
  • Head-of-line: Large response delays following requests.

2️⃣ HTTP/2

  • Binary frames over one TCP connection: multiplex streams.
  • Header compression (HPACK) saves bytes.
  • Still vulnerable to TCP-level HOL blocking if packet loss occurs.

3️⃣ HTTP/3 (QUIC)

  • Runs atop UDP with built-in encryption + congestion control.
  • Stream independence removes TCP HOL blocking latency waterfalls.
  • Connection migration: resume if client IP changes (mobile network switch).

πŸ” TLS 1.3 & Performance

  • Reduced round‑trips vs TLS 1.2; faster first byte.
  • 0‑RTT resumption: can send early data (idempotent only!).
  • Session tickets rotate keys; too many cause memory pressure.

πŸ”— Connection Strategies

  • Pooling: Limit concurrent connections per origin (browsers enforce caps).
  • Coalescing: HTTP/2 reuse across origins sharing certificate SANs.
  • Retry logic: Exponential backoff; beware retry storms on partial outages.

πŸ“Š Observability

  • TTFB: handshake + server generation time until first byte.
  • Waterfall charts: Reveal parallelization and blocking gaps.
  • Metrics: handshake duration, TLS reuse %, connection reuse %, 0‑RTT hit rate.
Terminal
curl -v https://example.com/product/42        # Show TLS + request/response
curl --http2 -I https://example.com           # Force HTTP/2, headers only
curl --http3 -I https://example.com           # Force HTTP/3 (if supported)
openssl s_client -connect example.com:443 -alpn h2,http/1.1  # ALPN negotiation
tcpdump -nn 'port 443'                        # Inspect SYN/SYN-ACK/ACK
traceroute example.com                        # Path latency context
Advanced: routing & sockets

πŸ”€ Reverse proxy routing

443 (Nginx) can route api.example.com β†’ localhost:8000, www.example.com β†’ localhost:3000, assets β†’ localhost:9000.

πŸ”Œ Ephemeral client ports

Each connection is a 4‑tuple (clientIP:clientPort ⇄ serverIP:serverPort), e.g. 198.51.100.24:53214 ⇄ 203.0.113.10:443.

🌍 Anycast/CDN

One advertised IP maps to multiple edges; DNS and BGP steer you to a close POP.

πŸ’¬ Communication Examples

GET β†— Outgoing

GET Request

A simple GET request to fetch a list of users. The client specifies it accepts JSON.

GET /api/users HTTP/1.1
Host: example.com
Accept: application/json
POST β†— Outgoing

POST Request

A POST request to create a new user. The body contains JSON data.

POST /api/users HTTP/1.1
Host: example.com
Content-Type: application/json

{"name":"Mehdi","role":"student"}
200 OK ↙ Incoming

Server Response

A successful response with caching headers, compression, and an ETag for revalidation.

HTTP/1.1 200 OK
Date: Thu, 06 Nov 2025 10:11:12 GMT
Content-Type: application/json; charset=utf-8
Cache-Control: max-age=60, public
ETag: "users:v1:af31b2"
Content-Encoding: br

[{"id":1,"name":"Mehdi"},{"id":2,"name":"Ada"}]
Start line Headers Blank line Body

Reading the response without the body: Status + headers already tell you success, cacheability, compression, and revalidation strategy (ETag). Monitoring tools often ignore the body entirely.

Beyond GET & POST: HTTP defines more methods β€” PUT (replace), PATCH (partial update), DELETE (remove). We'll use them all when building REST APIs in Module 5.

πŸ“¨ More Message Examples (HTML response, GET with query params)

GET with query parameters

GET /api/users?page=1 HTTP/1.1
Host: example.com
Accept: application/json

<!-- GET requests should not include a body -->

HTML Response

HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Cache-Control: max-age=120, public

<!doctype html>
<html>
  <head><title>Example</title></head>
  <body>
    <h1>Hello from the web server</h1>
  </body>
</html>

Legend: start line β€’ headers β€’ blank line β€’ body. Tip: GET requests do not include a body; use query parameters or POST for complex searches.

πŸ“¨ Anatomy of HTTP Messages

A message = start line + headers + optional body. Each part has distinct semantics.

Start Line
GET /api/users HTTP/1.1
Method + Path + Version (request) or Version + Status + Reason (response)
Headers
Host: example.com
Accept: application/json
Authorization: Bearer ...
Key: Value pairs. Control caching, auth, content type, routing.
Empty Line
↡
CRLF separator between headers and body. Required.
Body
{"name":"Mehdi","role":"student"}
Optional. Format defined by Content-Type. Can be JSON, HTML, binary, etc.

Intermediaries (proxies, load balancers) often ignore the body for routing decisions. They rely on headers for caching, retries, and compression.

πŸ“Š Status Codes: Semantics & Strategy

Status codes drive caching, retries, SEO, monitoring and auth flows before any body is read. Use precise codes consistently.

Range Meaning Common Codes
2xx Success 200 OK Β· 201 Created Β· 204 No Content Β· 206 Partial
3xx Redirect 301 Permanent Β· 302 Temp Β· 303 See Other Β· 304 Not Modified Β· 307/308 Preserve method
4xx Client Error 400 Bad Request Β· 401 Unauthorized Β· 403 Forbidden Β· 404 Not Found Β· 409 Conflict Β· 422 Unprocessable Β· 429 Too Many
5xx Server Error 500 Internal Β· 502 Bad Gateway Β· 503 Unavailable Β· 504 Timeout

Decision tree: (1) Did the request succeed? β†’ 2xx. (2) If not, is the fault on the client (4xx) or server (5xx)? (3) Pick the most specific code β€” never tunnel errors through 200.

πŸ“‹ Status Code Patterns (Design Guide)

πŸ” Auth vs Authorization

401 = "who are you?" Β· 403 = "I know you, but no"

  • 401 No/expired credentials β†’ include WWW-Authenticate.
  • 403 Credentials valid but action forbidden (scope/role).
  • Rule: Can supplying new credentials help? If yes β†’ 401, else 403.

βœ“ Validation & Semantics

400 = malformed Β· 422 = well-formed but invalid Β· 409 = conflict

  • 400 Malformed (parse/type error).
  • 422 Well-formed but domain rule failed.
  • 409 Version / uniqueness / state conflict.
  • 410 Resource intentionally removed (stop retrying).

πŸ’Ύ Caching & Conditionals

200 with ETag β†’ 304 on revalidation

  • 200 Fresh; send ETag/Cache-Control.
  • 304 Validator matched (If-None-Match/If-Modified-Since).
  • Rule: Always emit a strong validator for cacheable GETs.

πŸ”„ Retries & Resilience

502/503/504 are retryable Β· 500 may not be Β· 429 = back off

  • 502 Upstream error (dependency failed).
  • 503 Temporary overload / maintenance (add Retry-After).
  • 504 Upstream timeout.
  • Retry only idempotent methods (GET, HEAD, OPTIONS, safe DELETE, some PUT).

⏱️ Rate Limiting

  • 429 Too Many Requests (quota window exceeded).
  • Return: Retry-After, X-RateLimit-Remaining, X-RateLimit-Reset.
  • Rule: Use 429 (not 403) for transient quota exhaustion.
HTTP/2 429
Retry-After: 5
X-RateLimit-Remaining: 0
{"error":"rate_limit","retry_in":5}

πŸ“¦ Bulk / Partial

  • 207 Multi-Status (mixed results) OR
  • 200 with per-item status objects.
  • Prefer 200 + array unless spec needs 207.
{"results":[
  {"id":1,"status":201},
  {"id":2,"status":409,"error":"duplicate"}
]}

πŸ“₯ Ranges / Downloads

  • 206 Partial Content (serve byte range).
  • 416 Invalid range request.
HTTP/1.1 206 Partial Content
Content-Range: bytes 0-1023/4096

πŸ” Idempotent Mutations

  • PUT replace β†’ 200 (return body) or 204 (no body).
  • PATCH partial update β†’ 200/204; use 409 on version mismatch.
  • DELETE existing or already deleted β†’ often always 204 to be idempotent.

πŸ“‹ Error Envelope

  • Shape: { error, message?, details?, trace_id? }.
  • No stack traces in prod; supply correlation id.
  • Never use 200 with an error wrapper.
{"error":"conflict","message":"Version mismatch","expected_version":12}

Decision Cheatsheet

  • Malformed JSON: 400
  • Business rule fail: 422
  • Concurrent update: 409
  • Missing auth: 401
  • Not allowed: 403
  • Over capacity: 503 + Retry-After
  • Rate limited: 429
  • Removed resource: 410

πŸ“‹ Headers & Content Types

Headers = metadata. Start line + headers often decide caching, routing, and auth before the body is read.

🀝 Negotiation

Accept, Content-Type, Accept-Language

Client and server agree on format, language, and encoding of the response.

πŸ’Ύ Caching

Cache-Control, ETag, Last-Modified, Age

Controls how long responses are stored and when to revalidate with the server.

πŸ” Auth

Authorization, WWW-Authenticate

Carries credentials (tokens, API keys) so the server knows who you are.

πŸͺ Session

Cookie, Set-Cookie

Small data stored by the browser and sent automatically with every request to that domain.

πŸ“¦ Compression

Accept-Encoding, Content-Encoding

Reduces payload size over the wire. Server picks the best algorithm the client supports.

πŸ›‘οΈ Safety

Content-Security-Policy, HSTS, X-Frame-Options

Prevents XSS, clickjacking, and forces HTTPS. Set by the server in response headers.

🧭 Routing

Host, X-Forwarded-*, Traceparent

Determines which backend handles the request. Proxies add forwarding headers for origin info.

βœ‚οΈ Request Shaping

Range, If-None-Match, If-Modified-Since

Conditional requests and partial content. Avoid re-downloading unchanged resources.

πŸ“„ Deep Dive: Content Types & Representation

πŸ“€ Common Responses

HTML Β· JSON Β· XML Β· Images Β· PDF

πŸ“₯ Common Requests

JSON Β· Form URL Encoded Β· Multipart Β· Binary

πŸ”’ Versioning

  • Media type version (vnd.*+json)
  • Path / query

πŸ—œοΈ Compression

  • Textual formats compress well (gzip, brotli).
  • Pre-compress static assets for best performance.

Correctness: Wrong Content-Type breaks caches, confuses parsers, and can cause security issues. Be explicit; avoid guessing.

⚑ JavaScript Overview

βš™οΈ How JavaScript Works

πŸ“
Your Code
.js files
β†’
πŸ”§
JS Engine
V8, SpiderMonkey
β†’
⚑
Execution
Machine code
Single-Threaded
One task at a time
Event Loop
Handles async operations
ECMAScript
Language standard
Non-Blocking
Async I/O operations

JS engines (like V8, SpiderMonkey) implement the ECMAScript standard. JavaScript is single‑threaded with an event loop; asynchronous work uses callbacks, promises, and async/await.

Core Concepts at a Glance

πŸ“¦

Types & Variables

Primitives, type coercion, let/const, functions & arrow functions

stringnumberboolean() =>
πŸ—οΈ

Objects & Context

Object literals, prototypes, this binding, classes & constructor patterns

thisbindclassnew
πŸ“Š

Arrays & Iteration

Functional array methods, higher-order functions, transformations & reductions

mapfilterreducesort
⚑

Errors & Async

Exception handling, promises, async/await, error propagation patterns

try/catchPromiseasyncawait

Ready to learn JavaScript? Continue to Module 1: JS Language Core for variables, functions, objects, and more.

πŸš€ Node.js Overview

Node.js runs JavaScript on the server using Chrome's V8 engine plus system bindings for files, network, and OS access.

πŸš€ Node.js Architecture

πŸ“ Your JavaScript Code
↓
πŸ”§ Node.js APIs
fs, http, path, crypto…
↓
V8 Engine
JS execution
libuv
Async I/O
↓
πŸ’» Operating System
Files, Network, Processes
Common Use Cases
🌐 REST APIs ⚑ Real-time apps πŸ’» CLI tools πŸ”— Microservices

Node.js runs JavaScript on the server using the V8 engine plus system bindings for files, network, and more. It's great for I/O‑heavy apps where non-blocking asynchronous processing shines.

We'll explore Node.js in depth in Module 4: Node.js Fundamentals.

πŸ“ Summary

🌐 HTTP Protocol

A request/response protocol. Clients send requests, servers answer. Stateless by default.

πŸ–₯️ Client & Server

Client initiates requests, server listens and responds. Proxies, CDNs, and load balancers sit in between.

πŸ“¨ Messages

Start line + headers + optional body. Headers control everything before the body is read.

πŸ“Š Status Codes

2xx success, 3xx redirect, 4xx client error, 5xx server error. Be specific, never tunnel errors through 200.

πŸ“‹ Headers

Metadata key-value pairs. Control content negotiation, caching, auth, security, and compression.

⚑ JavaScript

Single-threaded with event loop. Runs in browsers (DOM) and on servers (Node.js).

🟒 Node.js

JavaScript runtime built on V8 + libuv. Non-blocking I/O, npm ecosystem, ideal for network services.

1
Next Module 1 / 7

Module 1: JavaScript Language Core

Variables, types, functions, arrow functions, callbacks, objects, and the this keyword.

var / let / const functions arrow => callbacks this objects
β†’