0% found this document useful (0 votes)
0 views66 pages

WebProgramming StudyNotes

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views66 pages

WebProgramming StudyNotes

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

BS CS Web Programming — Complete Study Notes Final Exam Preparation

BS Computer Science
Web Programming
Complete Study Notes

Final Exam Preparation · University-Level Depth · All 16 Weeks

Coverage All 16 Weeks — Foundations to Emerging Trends

Topics HTTP · HTML · CSS · JS · React · Redux · [Link] · Express · Databases · REST ·
Security · Performance · WebSockets · PWAs

Style First-principles explanations with code examples, exam Qs, viva Qs, and practice
problems

Standard MIT / Harvard academic depth in plain, clear language

Page 1
BS CS Web Programming — Complete Study Notes Final Exam Preparation

TABLE OF CONTENTS
Week Area Topics Covered

Week 1 Foundations Internet & WWW · HTTP Protocol · HTML

Week 2 Client-Side: CSS Selectors · Box Model · Responsive Design · Bootstrap / Tailwind

Week 3 JavaScript Fundamentals Core JS · Objects · ES6 · TypeScript

Week 4 DOM & jQuery DOM Manipulation · Events · jQuery · Client-Side Frameworks Overview

Week 5 React React Intro · Components · Props · State · Hooks

Week 6 Redux Redux Intro · Store · Actions · Reducers · Middleware

Week 7 Server-Side: [Link] Web Servers · [Link] · File System · Routing

Week 8 State & Architecture Cookies · Sessions · MVC · Hexagonal Architecture

Week 9 Express & Middleware Express Intro · Middleware · REST with Express

Week 10 Template Engines Pug · Nunjucks · Server-Side Rendering

Week 11 Databases MongoDB · MySQL · CRUD · ODM/ORM

Week 12 Other Frameworks Django · Laravel · Ruby on Rails overview

Week 13 Web Services SOA · REST · API Design · HTTP Methods

Week 14 Deployment & Security I Nginx · Apache · Cloud · SSL · Certificates

Week 15 Security II & Performance XSS · CSRF · HTTP/2 · HTTP/3 · SSR

Week 16 Emerging Trends WebSockets · WebAssembly · Progressive Web Apps

Page 2
BS CS Web Programming — Complete Study Notes Final Exam Preparation

WEEK 1 — FOUNDATIONS

Topic 1 · Internet and World Wide Web

1. Overview
The Internet is a global network of interconnected computers that communicate using standardised protocols.
The World Wide Web (WWW) is a system of interlinked documents and resources accessed over the
Internet through a browser. A key distinction: the Internet is the infrastructure (cables, routers, IP addresses).
The Web is one service that runs on top of it — just like how roads are infrastructure and taxis are a service
on top.
Tim Berners-Lee invented the Web in 1989 at CERN. His three core inventions: HTML (content structure),
HTTP (transfer protocol), and URLs (addresses). Before the Web, the Internet existed but was used mainly
for email and file transfer.

2. Core Concepts
IP Address
Every device on the Internet has a unique numerical address called an IP address. IPv4 looks like
[Link] (32-bit, ~4.3 billion addresses). IPv6 looks like 2001:0db8::1 (128-bit, effectively unlimited).

DNS — Domain Name System


DNS translates human-readable domain names ([Link]) into IP addresses ([Link]). Think of it
as the phone book of the Internet. Without DNS you would need to remember numbers for every site. DNS
runs on UDP port 53.

Packet Switching
Data is broken into small chunks called packets. Each packet may take a different route across the network
and they are reassembled at the destination. This makes the network fault-tolerant because there is no single
path that must stay intact.

Bandwidth vs Latency
Bandwidth is how much data can travel per second (think width of a pipe). Latency is how long a single
packet takes to travel from source to destination (think length of the pipe). A video call needs low latency. A
file download needs high bandwidth.

TCP/IP Model
Layer 4 — Application HTTP, HTTPS, DNS, FTP, WebSockets
Layer 3 — Transport TCP (reliable, ordered), UDP (fast, no guarantee)
Layer 2 — Internet IP addressing and routing
Layer 1 — Network Ethernet, WiFi (physical transmission)

TCP Three-Way Handshake


Before any HTTP data is sent, TCP establishes a reliable connection in three steps:
• SYN: Client says 'I want to connect'
• SYN-ACK: Server says 'OK, acknowledged'
• ACK: Client says 'Got it, we are connected'
This adds latency which is why HTTP/2 and HTTP/3 work to reduce round trips.

3. URL Structure

Page 3
BS CS Web Programming — Complete Study Notes Final Exam Preparation

[Link]

https = scheme / protocol


www = subdomain
example = domain name
.com = top-level domain (TLD)
:443 = port (default for HTTPS, usually hidden)
/products = path — resource location on server
?id=5 = query string — parameters passed to server
#reviews = fragment — handled by browser only, never sent to server

■ The fragment (#) is NEVER sent to the server. This is a classic exam trap.

4. DNS Resolution Flow


Browser cache -> OS cache -> ISP Resolver
-> Root Nameserver -> TLD Nameserver (.com)
-> Authoritative Nameserver -> IP returned to browser

Each result is cached with a TTL (Time To Live). When you change a domain's DNS, it can take up to 48
hours to propagate because caches at every level must expire first.

5. Full Request Lifecycle (what happens when you type a URL)


1. Browser checks own DNS cache
2. OS checks hosts file
3. Resolver (ISP / [Link]) is queried
4. Root -> TLD -> Authoritative nameserver lookup
5. IP address returned
6. TCP three-way handshake to server IP on port 443
7. TLS handshake (for HTTPS)
8. HTTP GET request sent
9. Server returns HTML
10. Browser parses HTML, finds CSS/JS/image links
11. Sub-resources fetched in parallel
12. Page rendered

6. Common Ports
Port Protocol / Service

80 HTTP

443 HTTPS

21 FTP

22 SSH

25 SMTP (email)

3306 MySQL

27017 MongoDB

3000 Common [Link] dev server

7. Common Exam Questions


• What is the difference between the Internet and the World Wide Web?
• Explain the role of DNS in web communication.
• What does each component of a URL represent? Give an example.

Page 4
BS CS Web Programming — Complete Study Notes Final Exam Preparation

• Describe the TCP three-way handshake.


• Trace step by step what happens when a user types a URL and presses Enter.
• What is the difference between IPv4 and IPv6?
• What is packet switching and why is it used over circuit switching?
• Why does changing a DNS record take up to 48 hours to propagate?

8. Common Mistakes
■ Confusing the Internet with the Web. They are not the same thing.
■ Thinking the URL fragment (#) is sent to the server. It never is.
■ Confusing HTTP (port 80) with HTTPS (port 443).
■ Thinking DNS only runs once. Every cache has a TTL and entries expire.
■ Thinking TCP and HTTP are the same layer. TCP is transport; HTTP rides on top.

9. Viva Questions
• If DNS is down but you know the IP, can you still reach the website?
• Can two websites share the same IP address? How?
• What is a reverse proxy and why is it used?
• What would break if ports did not exist?
• Why is UDP used for DNS instead of TCP?

Page 5
BS CS Web Programming — Complete Study Notes Final Exam Preparation

Topic 2 · HTTP Protocol

1. Overview
HTTP (HyperText Transfer Protocol) is the application-layer protocol that powers the Web. It defines how
clients (browsers) request resources and how servers respond. HTTP is stateless — every request is
independent and the server has no memory of previous requests without additional tools like cookies or
sessions.
HTTP/1.0 (1996) opened a new TCP connection for every request. HTTP/1.1 (1997) introduced persistent
connections (keep-alive). HTTP/2 (2015) introduced multiplexing and header compression. HTTP/3 (2022)
moved from TCP to QUIC (UDP-based) for lower latency.

2. HTTP Request Structure


GET /products?id=5 HTTP/1.1
Host: [Link]
Accept: text/html,application/xhtml+xml
Accept-Language: en-US,en;q=0.9
Cookie: session_id=abc123
Connection: keep-alive

[request body — only for POST/PUT/PATCH]

3. HTTP Response Structure


HTTP/1.1 200 OK
Content-Type: text/html; charset=UTF-8
Content-Length: 3425
Set-Cookie: session_id=abc123; HttpOnly; Secure
Cache-Control: max-age=3600

<!DOCTYPE html>
<html>...</html>

4. HTTP Methods
Method Purpose Has Body? Idempotent Safe?
?

GET Retrieve a resource No Yes Yes

POST Create a new resource Yes No No

PUT Replace a resource entirely Yes Yes No

PATCH Partially update a resource Yes No No

DELETE Remove a resource No Yes No

HEAD Like GET but no body returned No Yes Yes

OPTIONS Ask server what methods are supportedNo Yes Yes

✓ Idempotent: calling it multiple times has the same effect as calling it once. Safe: does not modify data.

5. HTTP Status Codes


Range Category Key Examples

1xx Informational 100 Continue, 101 Switching Protocols

Page 6
BS CS Web Programming — Complete Study Notes Final Exam Preparation

Range Category Key Examples

2xx Success 200 OK, 201 Created, 204 No Content

3xx Redirection 301 Moved Permanently, 302 Found, 304 Not Modified

4xx Client Error 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 429 Too Many Requests

5xx Server Error 500 Internal Server Error, 502 Bad Gateway, 503 Service Unavailable

6. Important HTTP Headers


Request headers
• Host — the domain name of the server (required in HTTP/1.1)
• Accept — what content types the client accepts (text/html, application/json)
• Authorization — credentials, e.g. Bearer token
• Content-Type — type of the request body (application/json, multipart/form-data)
• Cookie — sends stored cookies to the server

Response headers
• Content-Type — tells browser how to interpret the response
• Set-Cookie — instructs browser to store a cookie
• Cache-Control — tells browser and proxies how long to cache the response
• Location — used with 3xx redirects to tell client where to go
• Access-Control-Allow-Origin — CORS header controlling cross-origin access

7. HTTP vs HTTPS
HTTPS is HTTP with TLS (Transport Layer Security) on top. TLS encrypts the data in transit so
eavesdroppers cannot read it. It also authenticates the server using a digital certificate so you know you are
talking to the real server and not an impostor. All modern web applications must use HTTPS.
HTTP flow:
Client -> TCP handshake -> HTTP request (PLAINTEXT) -> Server

HTTPS flow:
Client -> TCP handshake -> TLS handshake (cert, keys) -> Encrypted HTTP -> Server

8. HTTP Versions Comparison


Version Year Key Feature Transport

HTTP/1.0 1996 New TCP connection per request TCP

HTTP/1.1 1997 Persistent connections, pipelining TCP

HTTP/2 2015 Multiplexing, header compression, server push TCP

HTTP/3 2022 QUIC-based, lower latency, no head-of-line block UDP (QUIC)

9. Statelessness and How to Work Around It


HTTP is stateless — the server does not remember previous requests. A logged-in user sending request #2
looks identical to an anonymous user. To maintain state:
• Cookies — small pieces of data stored in the browser and sent with every request
• Sessions — server-side storage keyed by a session ID sent in a cookie
• JWT tokens — signed tokens sent in the Authorization header
• URL parameters — state embedded in the URL (not secure for sensitive data)

Page 7
BS CS Web Programming — Complete Study Notes Final Exam Preparation

10. Common Exam Questions


• What does it mean that HTTP is stateless? What problems does this cause?
• Explain the difference between GET and POST requests with examples.
• What is the difference between 401 and 403 status codes?
• What is the role of the Content-Type header?
• Describe the difference between HTTP/1.1 and HTTP/2.
• What happens during a TLS handshake?
• What is the difference between idempotent and safe HTTP methods?
• Why should modern applications always use HTTPS?

11. Common Mistakes


■ Thinking GET can never have a body. It technically can but should not by convention.
■ Confusing 401 Unauthorized (not authenticated) with 403 Forbidden (authenticated but not allowed).
■ Thinking HTTPS changes the HTTP protocol — it only adds encryption on top.
■ Assuming POST is always for form submissions. It is used for any creation operation including API calls.

Page 8
BS CS Web Programming — Complete Study Notes Final Exam Preparation

Topic 3 · HTML — HyperText Markup Language

1. Overview
HTML is the standard markup language for creating web pages. It defines the structure and meaning
(semantics) of web content using a system of elements represented by tags. HTML is not a programming
language — it has no logic, variables, or functions. It only describes what content exists and what type it is.

2. Document Structure
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Page Title</title>
<link rel="stylesheet" href="[Link]">
</head>
<body>
<h1>Hello World</h1>
<script src="[Link]"></script>
</body>
</html>

• DOCTYPE declaration tells the browser to use modern standards mode (not quirks mode)
• head contains metadata, not visible content
• meta charset=UTF-8 ensures proper character encoding globally
• viewport meta tag is essential for responsive design on mobile
• Scripts placed at bottom of body so HTML renders before JS executes

3. Semantic HTML
Semantic elements clearly describe their meaning to the browser, developer, and assistive technologies.
Using them improves accessibility, SEO, and maintainability.
<!-- Non-semantic (avoid) -->
<div class="header">...</div>
<div class="nav">...</div>
<div class="main">...</div>

<!-- Semantic (preferred) -->


<header>...</header>
<nav>...</nav>
<main>
<article>...</article>
<aside>...</aside>
</main>
<footer>...</footer>

Element Purpose

<header> Site or section header

<nav> Navigation links

<main> Main content of the page (unique per page)

<article> Self-contained content (blog post, news article)

Page 9
BS CS Web Programming — Complete Study Notes Final Exam Preparation

Element Purpose

<section> Themed grouping of content

<aside> Sidebar / tangentially related content

<footer> Site or section footer

<figure> Image/diagram with optional caption

<time> Machine-readable date/time

<mark> Highlighted text

4. Forms
<form action="/login" method="POST">
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>

<label for="password">Password:</label>
<input type="password" id="password" name="password" required>

<input type="checkbox" id="remember" name="remember">


<label for="remember">Remember me</label>

<button type="submit">Login</button>
</form>

• action — where to send the form data (URL)


• method — GET (data in URL) or POST (data in body)
• label for= must match input id= for accessibility
• required, minlength, pattern — HTML5 validation attributes
• type=email, type=number, type=date — trigger appropriate mobile keyboards

5. HTML5 Key Features


• Semantic elements (header, nav, main, article, section, footer, aside)
• Canvas and SVG — for drawing graphics directly in the browser
• Audio and Video elements — native media playback without plugins
• Local Storage and Session Storage — client-side data storage
• Geolocation API — access user location with permission
• Web Workers — run JavaScript in background threads
• Custom data attributes — data-* for storing custom data on elements
<div data-user-id="42" data-role="admin">
<!-- Access in JS: [Link] -->
</div>

6. Block vs Inline Elements


Block elements start on a new line and take full width. Inline elements flow within text and only take their
content width.
• Block: div, p, h1-h6, ul, ol, li, table, form, header, section, article
• Inline: span, a, strong, em, img, input, button, label
• Inline-block: behaves inline but allows width/height to be set

7. Common Exam Questions


• What is the difference between semantic and non-semantic HTML?

Page 10
BS CS Web Programming — Complete Study Notes Final Exam Preparation

• Why is the DOCTYPE declaration important?


• What is the difference between the id and class attributes?
• Explain the difference between GET and POST in an HTML form.
• What are data-* attributes and when would you use them?
• What is the difference between block and inline elements?
• Why should the viewport meta tag be included in all responsive pages?

8. Common Mistakes
■ Using divs for everything instead of semantic elements.
■ Putting a block element (like p or div) inside an inline element (like span or a).
■ Omitting label elements — this breaks screen readers and accessibility.
■ Using inline styles everywhere — this should be reserved for dynamic JS styling.
■ Confusing the id attribute (must be unique per page) with class (reusable).

Page 11
BS CS Web Programming — Complete Study Notes Final Exam Preparation

WEEK 2 — CLIENT-SIDE PROGRAMMING: CSS

Topic 4 · CSS Fundamentals: Selectors, Specificity, Box Model,


Positioning

1. Overview
CSS (Cascading Style Sheets) controls the visual presentation of HTML documents. It separates content
(HTML) from presentation (CSS), making pages easier to maintain. The 'cascading' refers to the set of rules
that determines which style wins when multiple rules target the same element.

2. The Cascade, Inheritance, and Specificity


When multiple CSS rules target the same element, the browser uses three mechanisms to decide which
wins:
• Specificity — more specific selectors beat less specific ones
• Source order — when specificity is equal, the last rule wins
• Inheritance — some properties (color, font-size) are inherited by children. Others (border, margin) are not.

Specificity calculation
Inline styles 1,0,0,0 (highest)
ID selectors 0,1,0,0 e.g. #header
Class / pseudo-class 0,0,1,0 e.g. .btn :hover
Element / pseudo-elem 0,0,0,1 e.g. p ::before
Universal selector 0,0,0,0 e.g. *

Example: #nav .menu li => 0,1,1,1


Example: .[Link] => 0,0,2,0 (beats .btn which is 0,0,1,0)

■ !important overrides all specificity. It should almost never be used — it makes debugging a nightmare.

3. Selector Types
/* Element */ p { color: red; }
/* Class */ .card { border: 1px solid; }
/* ID */ #logo { width: 200px; }
/* Attribute */ input[type='email'] { border-color: blue; }
/* Pseudo-class */ a:hover { color: orange; }
/* Pseudo-element */ p::first-line { font-weight: bold; }
/* Descendant */ nav a { text-decoration: none; }
/* Child */ ul > li { list-style: none; }
/* Adjacent sibling */ h2 + p { margin-top: 0; }
/* General sibling */ h2 ~ p { color: gray; }
/* Universal */ * { box-sizing: border-box; }

4. The Box Model


Every HTML element is a rectangular box. The box model describes the layers that make up that box from
inside out:
+----------------------------------+
| MARGIN | <- Outside the element, transparent
| +----------------------------+ |
| | BORDER | | <- The visible border
| | +----------------------+ | |
| | | PADDING | | | <- Space inside border, background colour shows

Page 12
BS CS Web Programming — Complete Study Notes Final Exam Preparation

| | | +----------------+ | | |
| | | | CONTENT | | | | <- Where text/images go
| | | +----------------+ | | |
| | +----------------------+ | |
| +----------------------------+ |
+----------------------------------+

/* Standard model: width only includes content */


box-sizing: content-box; /* default */

/* Border-box: width includes padding AND border */


box-sizing: border-box; /* recommended for all elements */
* { box-sizing: border-box; }

✓ Always set * { box-sizing: border-box; } globally. It makes layout math predictable.

5. Display Property
Value Behaviour

block Full width, new line before/after, width/height settable

inline Flows with text, width/height NOT settable

inline-block Flows with text but width/height ARE settable

flex Flexbox container — powerful 1D layout

grid Grid container — powerful 2D layout

none Removes element from layout entirely (not just invisible)

6. Positioning
position: static; /* default — follows normal document flow */
position: relative; /* offset from its normal position */
position: absolute; /* removed from flow, positioned relative to nearest
positioned ancestor (not static) */
position: fixed; /* removed from flow, positioned relative to viewport.
Stays on screen when scrolling */
position: sticky; /* static until scroll threshold, then fixed */

/* Practical example: modal overlay */


.overlay {
position: fixed;
top: 0; left: 0;
width: 100%; height: 100%;
background: rgba(0,0,0,0.5);
z-index: 1000;
}
.modal {
position: absolute;
top: 50%; left: 50%;
transform: translate(-50%, -50%);
}

7. Flexbox
Flexbox solves one-dimensional layout — arranging items in a row or column. The parent is the flex
container; children are flex items.

Page 13
BS CS Web Programming — Complete Study Notes Final Exam Preparation

.container {
display: flex;
flex-direction: row; /* row (default) | column */
justify-content: space-between; /* main axis alignment */
align-items: center; /* cross axis alignment */
flex-wrap: wrap; /* allow items to wrap */
gap: 16px; /* space between items */
}
.item {
flex: 1; /* grow to fill equal space */
}

8. CSS Grid
CSS Grid solves two-dimensional layout — rows AND columns at the same time.
.grid {
display: grid;
grid-template-columns: 1fr 2fr 1fr; /* 3 columns, middle twice as wide */
grid-template-rows: auto; /* rows sized by content */
gap: 20px;
}
.hero {
grid-column: 1 / -1; /* span all columns */
}
.sidebar {
grid-column: 3;
grid-row: 2 / 4; /* span rows 2 to 4 */
}

9. CSS Variables (Custom Properties)


:root {
--primary-color: #1B4F8A;
--font-size-base: 16px;
--spacing-md: 16px;
}
.button {
background: var(--primary-color);
font-size: var(--font-size-base);
padding: var(--spacing-md);
}

10. Common Exam Questions


• Explain how CSS specificity is calculated with an example.
• What is the difference between content-box and border-box?
• What is the difference between display:none and visibility:hidden?
• Explain the difference between position:absolute and position:fixed.
• When would you use Flexbox vs CSS Grid?
• What does 'cascading' mean in CSS?
• What is the difference between a pseudo-class and a pseudo-element?
• How does the z-index property work and what are stacking contexts?

11. Common Mistakes


■ Forgetting to set position on a parent when using position:absolute on a child. Absolute positioning climbs up
to the first non-static ancestor.

Page 14
BS CS Web Programming — Complete Study Notes Final Exam Preparation

■ Using !important everywhere to fix specificity issues instead of writing better selectors.
■ Confusing margin (outside the element) with padding (inside the element).
■ Using display:none to 'hide' something that is still needed for accessibility — screen readers skip display:none
entirely.

Page 15
BS CS Web Programming — Complete Study Notes Final Exam Preparation

Topic 5 · Responsive Design and CSS Frameworks

1. Responsive Web Design


Responsive design means a single codebase adapts its layout to different screen sizes. The three pillars are:
fluid grids, flexible images, and media queries.

Media Queries
/* Mobile-first approach — base styles for small screens */
.container { width: 100%; padding: 16px; }

/* Tablet — 768px and up */


@media (min-width: 768px) {
.container { max-width: 960px; margin: 0 auto; }
}

/* Desktop — 1200px and up */


@media (min-width: 1200px) {
.container { max-width: 1400px; }
}

/* Responsive typography */
@media (prefers-color-scheme: dark) {
body { background: #111; color: #eee; }
}

✓ Mobile-first is the industry standard. Write base styles for mobile, then use min-width queries to enhance for
larger screens. It is easier to add complexity than to remove it.

Fluid units
• % — percentage of parent element
• vw / vh — percentage of viewport width / height
• em — relative to parent font-size
• rem — relative to root font-size (html element). Preferred for font sizing.
• clamp(min, preferred, max) — responsive value with limits
font-size: clamp(1rem, 2.5vw, 2rem); /* fluid font between 1rem and 2rem */

2. Bootstrap
Bootstrap is a CSS framework by Twitter. It provides a grid system, utility classes, and pre-built components
(buttons, navbars, modals, cards). It uses a 12-column responsive grid.
<!-- Bootstrap 5 CDN -->
<link href="[Link]
rel="stylesheet">

<!-- 12-column grid example -->


<div class="container">
<div class="row">
<div class="col-12 col-md-8">Main content</div> <!-- full on mobile, 8/12 on tablet+ -->
<div class="col-12 col-md-4">Sidebar</div> <!-- full on mobile, 4/12 on tablet+ -->
</div>
</div>

<!-- Bootstrap breakpoints -->


xs < 576px
sm >= 576px

Page 16
BS CS Web Programming — Complete Study Notes Final Exam Preparation

md >= 768px
lg >= 992px
xl >= 1200px
xxl >= 1400px

3. Tailwind CSS
Tailwind is a utility-first CSS framework. Instead of pre-built components, it gives you low-level utility classes
that you compose directly in HTML. No custom CSS is usually needed.
<!-- Tailwind card example -->
<div class="max-w-sm rounded overflow-hidden shadow-lg bg-white p-6">
<h2 class="text-xl font-bold text-gray-900 mb-2">Card Title</h2>
<p class="text-gray-600 text-sm">Description text here.</p>
<button class="mt-4 bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded">
Click me
</button>
</div>

4. Bootstrap vs Tailwind Comparison


Feature Bootstrap Tailwind CSS

Approach Component-based Utility-first

Learning curve Low — quick to start Medium — need to learn utility classes

Customisation Override default styles Configure design tokens in config file

Bundle size Larger (unused CSS included) Very small with purge/JIT

Design freedom Opinionated look Full design freedom

Best for Rapid prototyping Custom design systems

5. Cross-Browser Compatibility
Different browsers (Chrome, Firefox, Safari, Edge) implement CSS features at different times. Strategies:
• Vendor prefixes — -webkit- (Chrome/Safari), -moz- (Firefox), -ms- (IE/Edge)
• Can I Use ([Link]) — check feature support across browsers
• Autoprefixer — PostCSS plugin that adds vendor prefixes automatically
• CSS resets / [Link] — remove browser default inconsistencies
• Progressive enhancement — build base that works everywhere, enhance for modern browsers
/* Vendor prefix example */
.box {
-webkit-transform: rotate(45deg); /* old Chrome/Safari */
-moz-transform: rotate(45deg); /* old Firefox */
transform: rotate(45deg); /* modern standard */
}

6. Common Exam Questions


• What is responsive web design and what are its three pillars?
• Explain mobile-first design. Why is it preferred over desktop-first?
• What is the Bootstrap grid system? How does the 12-column layout work?
• Compare Bootstrap and Tailwind CSS.
• What is a CSS breakpoint and how is one implemented?
• What is the difference between em and rem units?

Page 17
BS CS Web Programming — Complete Study Notes Final Exam Preparation

• How does the clamp() function make typography responsive?

Page 18
BS CS Web Programming — Complete Study Notes Final Exam Preparation

WEEK 3 — JAVASCRIPT FUNDAMENTALS

Topic 6 · JavaScript Core Concepts, Objects, ES6+, and TypeScript

1. Overview
JavaScript is the only programming language natively understood by web browsers. It makes pages
interactive by responding to events, manipulating the DOM, and communicating with servers. JavaScript is
single-threaded, event-driven, and non-blocking. It also runs on servers via [Link].

2. Data Types
// Primitive types
let name = 'Alice'; // string
let age = 25; // number (integers AND floats are the same type)
let isLoggedIn = true; // boolean
let nothing = null; // null — intentional absence of value
let notDefined; // undefined — variable declared but not assigned
let id = Symbol('id'); // symbol — unique identifier
let big = 9007199254740991n; // bigint — for very large integers

// Reference types
let arr = [1, 2, 3]; // Array
let obj = { x: 1, y: 2 }; // Object
let fn = function() {}; // Function

✓ typeof null returns 'object' — this is a famous JavaScript bug that was never fixed for backwards compatibility.

3. var, let, and const


var x = 1; // function-scoped, hoisted, can be redeclared (avoid)
let y = 2; // block-scoped, not hoisted to usable state, can be reassigned
const z = 3; // block-scoped, must be assigned at declaration, cannot be reassigned

// const with objects — the variable cannot be reassigned


// but the object's PROPERTIES can still be modified
const user = { name: 'Alice' };
[Link] = 'Bob'; // OK
user = {}; // TypeError — cannot reassign a const

Feature var let const

Scope Function Block Block

Hoisting Yes (undef) Yes (TDZ) Yes (TDZ)

Re-declare Yes No No

Re-assign Yes Yes No

Use today? Avoid Yes Preferred

4. Functions
// Function declaration (hoisted)
function add(a, b) { return a + b; }

// Function expression (not hoisted)

Page 19
BS CS Web Programming — Complete Study Notes Final Exam Preparation

const subtract = function(a, b) { return a - b; };

// Arrow function (ES6) — concise, no own 'this'


const multiply = (a, b) => a * b;

// Default parameters (ES6)


function greet(name = 'World') { return `Hello, ${name}!`; }

// Rest parameters (ES6)


function sum(...numbers) {
return [Link]((acc, n) => acc + n, 0);
}
sum(1, 2, 3, 4); // 10

5. JavaScript Objects
// Object literal
const person = {
name: 'Alice',
age: 30,
greet() {
return `Hi, I'm ${[Link]}`;
}
};

// Accessing properties
[Link]; // dot notation
person['name']; // bracket notation (useful for dynamic keys)

// Object destructuring (ES6)


const { name, age } = person;

// Spread operator (ES6)


const updated = { ...person, age: 31 }; // creates new object with age updated

// Computed property names (ES6)


const key = 'status';
const obj = { [key]: 'active' }; // { status: 'active' }

6. Prototypes and Classes


JavaScript uses prototype-based inheritance. Every object has an internal link to a prototype object. ES6
classes are syntactic sugar over this prototype system — they look like Java/C++ classes but work differently
under the hood.
// ES6 Class
class Animal {
constructor(name) {
[Link] = name;
}
speak() {
return `${[Link]} makes a sound.`;
}
}

class Dog extends Animal {


speak() {

Page 20
BS CS Web Programming — Complete Study Notes Final Exam Preparation

return `${[Link]} barks.`;


}
}

const d = new Dog('Rex');


[Link](); // 'Rex barks.'
d instanceof Dog; // true
d instanceof Animal; // true

7. Key ES6+ Features


Template literals
const msg = `Hello, ${[Link]}! You have ${count} messages.`;

Destructuring
const [first, second, ...rest] = [1, 2, 3, 4, 5];
const { a, b: renamed, c = 'default' } = { a: 1, b: 2 };

Promises and async/await


// Promise
fetch('/api/users')
.then(res => [Link]())
.then(data => [Link](data))
.catch(err => [Link](err));

// Async/await (cleaner syntax for the same thing)


async function getUsers() {
try {
const res = await fetch('/api/users');
const data = await [Link]();
return data;
} catch (err) {
[Link](err);
}
}

Modules (ES6 import/export)


// [Link]
export const PI = 3.14159;
export function add(a, b) { return a + b; }
export default class Calculator { ... }

// [Link]
import Calculator, { PI, add } from './[Link]';

Array methods
const nums = [1, 2, 3, 4, 5];
[Link](n => n * 2); // [2, 4, 6, 8, 10]
[Link](n => n % 2 === 0); // [2, 4]
[Link]((sum, n) => sum + n, 0); // 15
[Link](n => n > 3); // 4 (first match)
[Link](n => n > 0); // true
[Link](n => n > 4); // true

8. Closures and Scope

Page 21
BS CS Web Programming — Complete Study Notes Final Exam Preparation

A closure is a function that remembers the variables from its outer scope even after that scope has finished
executing. Closures are fundamental to callbacks, event handlers, and module patterns.
function makeCounter() {
let count = 0; // count lives in makeCounter's scope
return function() {
count++; // inner function 'closes over' count
return count;
};
}

const counter = makeCounter();


counter(); // 1
counter(); // 2 — count is remembered between calls

9. The Event Loop


JavaScript is single-threaded but handles async operations through the event loop. Understanding it is critical
for understanding why async code behaves as it does.
Call Stack Web APIs Callback Queue
(synchronous execution) (async work) (waiting to run)
| | |
main() setTimeout, [callback1]
fetch() ------> ------> fetch, DOM events [callback2]
done? --> --> pushed to stack

[Link]('A'); // prints: A
setTimeout(() => [Link]('B'), 0); // pushed to queue
[Link]('C'); // prints: C
// B prints last even though timeout is 0ms

10. TypeScript
TypeScript is a superset of JavaScript developed by Microsoft. It adds optional static typing, interfaces,
generics, and other features that make large codebases easier to maintain. TypeScript compiles (transpiles)
to plain JavaScript before running.
// TypeScript examples
let name: string = 'Alice';
let age: number = 30;
let scores: number[] = [90, 85, 92];

// Interface
interface User {
id: number;
name: string;
email?: string; // optional property
}

// Function with types


function greet(user: User): string {
return `Hello, ${[Link]}`;
}

// Generics
function first<T>(arr: T[]): T | undefined {
return arr[0];
}

Page 22
BS CS Web Programming — Complete Study Notes Final Exam Preparation

first<number>([1, 2, 3]); // returns 1


first<string>(['a', 'b']); // returns 'a'

Why TypeScript?
• Catches type errors at compile time instead of at runtime in production
• Better IDE support — autocomplete, inline docs, refactoring tools
• Makes large codebases with many developers much safer to work on
• Self-documenting code — function signatures show exactly what types are expected

11. Common Exam Questions


• What is the difference between == and ===?
• Explain closures with an example.
• What is hoisting? How does it differ for var, let, and const?
• What is the event loop and how does JavaScript handle asynchronous code?
• What is the difference between a Promise and async/await?
• What are arrow functions and how do they differ from regular functions regarding 'this'?
• What is prototypal inheritance?
• What are the main advantages of TypeScript over JavaScript?
• Explain the difference between null and undefined.

12. Common Mistakes


■ Using == instead of ===. The double equals coerces types (0 == '0' is true). Always use ===.
■ Thinking const means the value is immutable. const prevents reassignment of the variable, not mutation of the
object.
■ Misunderstanding 'this' in arrow functions. Arrow functions inherit 'this' from the surrounding context. They do
not have their own 'this'.
■ Forgetting that async functions always return a Promise, even if you return a plain value.

Page 23
BS CS Web Programming — Complete Study Notes Final Exam Preparation

WEEK 4 — DOM MANIPULATION, JQUERY &


CLIENT-SIDE FRAMEWORKS

Topic 7 · DOM Manipulation with JavaScript and jQuery

1. What is the DOM?


The Document Object Model (DOM) is a tree-structured representation of an HTML document that the
browser creates in memory. JavaScript uses the DOM API to read, add, change, or remove elements and
attributes — changing the DOM is what makes pages interactive without a full page reload.
HTML file on disk DOM in browser memory
<html> document
<body> body
<h1>Hello</h1> => h1 -> 'Hello'
<p>World</p> p -> 'World'
</body>
</html>

2. Selecting Elements
// Modern selectors (preferred)
[Link]('#header'); // returns first match (CSS selector)
[Link]('.card'); // returns NodeList of all matches

// Older API (still common)


[Link]('header'); // by ID (fastest)
[Link]('card'); // HTMLCollection
[Link]('p'); // HTMLCollection

3. Manipulating Elements
const el = [Link]('#box');

// Content
[Link] = 'New text'; // safe — escapes HTML
[Link] = '<b>Bold</b>'; // renders HTML — XSS risk if user input!

// Attributes
[Link]('data-id', '42');
[Link]('class');
[Link]('disabled');

// Classes
[Link]('active');
[Link]('active');
[Link]('open');
[Link]('active'); // true/false

// Styles
[Link] = 'red';
[Link] = 'none';

// Creating and inserting elements


const newEl = [Link]('div');

Page 24
BS CS Web Programming — Complete Study Notes Final Exam Preparation

[Link] = 'I am new';


[Link](newEl); // add as last child
[Link](newEl); // add as first child
[Link](); // remove element from DOM

4. Events
const btn = [Link]('#submit-btn');

// Add event listener (modern approach)


[Link]('click', function(event) {
[Link](); // prevent form submission / link navigation
[Link](); // stop event bubbling up the DOM
[Link]('clicked!', [Link]);
});

// Common events
// click, dblclick, mouseover, mouseout, mousedown, mouseup
// keydown, keyup, keypress
// submit, change, input, focus, blur
// scroll, resize, load, DOMContentLoaded

Event Bubbling and Capturing


When you click an element, the event fires on that element AND bubbles up through all its ancestors to the
document. Event delegation uses this: attach one listener to a parent to handle events for many children,
including dynamically added ones.
// Event delegation — handles clicks on ALL .card elements
// even ones added to the DOM after this code runs
[Link]('.card-container').addEventListener('click', (e) => {
if ([Link]('card')) {
[Link]('Card clicked:', [Link]);
}
});

5. jQuery
jQuery is a JavaScript library that simplifies DOM manipulation, event handling, and AJAX calls. It abstracts
away browser inconsistencies. While React/Vue have replaced jQuery in modern SPAs, it still runs on the
majority of websites on the internet (including WordPress sites).
// Selecting
$('#header'); // same as [Link]('#header')
$('.card'); // all elements with class 'card'

// Manipulation
$('#box').text('Hello');
$('#box').html('<b>Bold</b>');
$('#box').addClass('active');
$('#box').css({ color: 'red', fontSize: '16px' });
$('#box').hide();
$('#box').show();
$('#box').fadeIn(500);

// Events
$('#btn').on('click', function() {
$(this).toggleClass('active');

Page 25
BS CS Web Programming — Complete Study Notes Final Exam Preparation

});

// AJAX
$.ajax({
url: '/api/users',
method: 'GET',
success: function(data) { [Link](data); },
error: function(err) { [Link](err); }
});

// Modern shorthand
$.get('/api/users').done(data => [Link](data));

6. Vanilla JS vs jQuery
Task Vanilla JS jQuery

Select [Link]('.el') $('.el')

Add class [Link]('x') $('.el').addClass('x')

AJAX GET fetch('/url').then(...) $.get('/url').done(...)

Hide [Link]='none' $('.el').hide()

On click [Link]('click',f) $('.el').on('click', f)

7. Overview of Client-Side Frameworks


Framework Type Key Idea Used by

React Library Component-based UI, Virtual DOM Meta, Airbnb, Netflix

Vue Framework Progressive, gentle learning curve Alibaba, Xiaomi

Angular Framework Full MVC, TypeScript-first, opinionated Google, enterprise apps

Svelte Compiler No virtual DOM — compiles to vanilla JS Smaller projects

jQuery Library DOM manipulation, browser compat Legacy / WordPress

8. Common Exam Questions


• What is the DOM and how is it different from the HTML source file?
• What is event bubbling? How does event delegation use it?
• What is the difference between innerHTML and textContent?
• Why should you avoid using innerHTML with user-supplied input?
• What does [Link]() do?
• Compare vanilla JavaScript DOM manipulation with jQuery.
• What is the difference between DOMContentLoaded and the load event?

Page 26
BS CS Web Programming — Complete Study Notes Final Exam Preparation

WEEK 5 — INTRODUCTION TO REACT AND UI


COMPONENTS

Topic 8 · React: Components, Props, State, and Hooks

1. Overview
React is a JavaScript library built by Facebook (Meta) for building user interfaces. Its key insight: describe
WHAT the UI should look like for a given state, and React figures out the minimal DOM changes needed.
This declarative approach is far easier to reason about than imperative jQuery-style code.
React uses a Virtual DOM — a lightweight copy of the real DOM in memory. When state changes, React
re-renders the virtual DOM, diffs it against the previous version, and applies only the minimal set of real DOM
changes needed.

2. JSX
JSX is a syntax extension that lets you write HTML-like code inside JavaScript. Babel transforms JSX into
plain JavaScript before it runs in the browser.
// JSX
const element = <h1 className="title">Hello, {[Link]}!</h1>;

// What Babel transforms it to:


const element = [Link]('h1', { className: 'title' }, 'Hello, ', [Link],
'!');

• Use className instead of class (class is a reserved JS keyword)


• Use htmlFor instead of for on label elements
• JSX expressions go inside curly braces: {expression}
• All JSX must have a single root element — use <> (Fragment) to avoid extra divs

3. Components
A component is a reusable, self-contained piece of UI. Think of components as custom HTML elements you
define yourself. Modern React uses function components exclusively.
// Function component (modern standard)
function UserCard({ name, email, avatar }) {
return (
<div className="card">
<img src={avatar} alt={name} />
<h2>{name}</h2>
<p>{email}</p>
</div>
);
}

// Using the component


<UserCard
name="Alice"
email="alice@[Link]"
avatar="/img/[Link]"
/>

4. Props

Page 27
BS CS Web Programming — Complete Study Notes Final Exam Preparation

Props (properties) are how a parent component passes data down to a child component. Props are read-only
— a component should never modify its own props. Data flows one way: parent to child.
function Button({ label, onClick, variant = 'primary', disabled = false }) {
return (
<button
className={`btn btn-${variant}`}
onClick={onClick}
disabled={disabled}
>
{label}
</button>
);
}

// Usage
<Button label="Save" onClick={() => save()} />
<Button label="Delete" onClick={() => del()} variant="danger" />

5. State and useState Hook


State is data that belongs to a component and can change over time. When state changes, React re-renders
the component. You declare state using the useState hook.
import { useState } from 'react';

function Counter() {
const [count, setCount] = useState(0); // [currentValue, setter]

return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>+</button>
<button onClick={() => setCount(count - 1)}>-</button>
<button onClick={() => setCount(0)}>Reset</button>
</div>
);
}

■ Never modify state directly ([Link] = x). Always use the setter (setState). Direct mutation does not trigger
re-renders.

6. useEffect Hook
useEffect runs side effects — things that happen outside of rendering. Fetching data, setting up
subscriptions, manually updating the DOM, or setting timers.
import { useState, useEffect } from 'react';

function UserProfile({ userId }) {


const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);

useEffect(() => {
// This runs after every render where userId changed
setLoading(true);
fetch(`/api/users/${userId}`)
.then(r => [Link]())
.then(data => {

Page 28
BS CS Web Programming — Complete Study Notes Final Exam Preparation

setUser(data);
setLoading(false);
});

// Cleanup function (runs before next effect or on unmount)


return () => {
// cancel requests, clear timers, etc.
};
}, [userId]); // dependency array — effect only re-runs when userId changes

if (loading) return <p>Loading...</p>;


return <div>{[Link]}</div>;
}

✓ Dependency array rules: [] = run once on mount. [x] = run when x changes. No array = run after every render
(usually wrong).

7. Other Core Hooks


// useContext — access context without prop drilling
const theme = useContext(ThemeContext);

// useRef — mutable reference that does NOT trigger re-renders


const inputRef = useRef(null);
<input ref={inputRef} />
[Link](); // programmatically focus

// useMemo — memoize expensive computation


const sortedList = useMemo(() => {
return [Link]((a, b) => [Link]([Link]));
}, [items]);

// useCallback — memoize a function (stable reference)


const handleClick = useCallback(() => {
doSomething(id);
}, [id]);

8. Component Lifecycle (via useEffect)


useEffect(() => {
// ComponentDidMount — runs once after first render
}, []);

useEffect(() => {
// ComponentDidUpdate — runs after every render
});

useEffect(() => {
return () => {
// ComponentWillUnmount — cleanup when component leaves DOM
};
}, []);

9. Lifting State Up
When two sibling components need to share state, move the state up to their closest common parent. The
parent holds the state and passes it down as props. This is the primary way to share data between

Page 29
BS CS Web Programming — Complete Study Notes Final Exam Preparation

components in React.

10. Key vs Index in Lists


// WRONG — using index as key causes bugs when list is reordered
[Link]((item, index) => <Item key={index} data={item} />)

// CORRECT — use a stable unique ID


[Link](item => <Item key={[Link]} data={item} />)

■ Using array index as key is a common mistake. If the list can be reordered, filtered, or items can be deleted,
index as key causes incorrect component reuse and state bugs.

11. Common Exam Questions


• What is the Virtual DOM and why does React use it?
• What is the difference between state and props?
• Explain the purpose of the useEffect dependency array.
• What is lifting state up and why is it necessary?
• Why do we need a key prop when rendering lists?
• What is JSX and how does it get transformed?
• What is the difference between a controlled and uncontrolled component?
• Explain the difference between useMemo and useCallback.

Page 30
BS CS Web Programming — Complete Study Notes Final Exam Preparation

WEEK 6 — REDUX: STATE MANAGEMENT

Topic 9 · Redux: Store, Actions, Reducers, and Middleware

1. The Problem Redux Solves


In large React apps, many components need access to the same data (e.g. the logged-in user). Lifting state
up to a common ancestor and passing it down through many levels of components (prop drilling) becomes
unmanageable. Redux solves this by providing a single, centralised store that any component can read from
or write to.

2. Core Concepts
• Store — a single JavaScript object that holds the entire application state
• Action — a plain object describing what happened. Must have a 'type' field. Example: { type:
'INCREMENT', payload: 1 }
• Reducer — a pure function (state, action) => newState. Takes the current state and an action, returns the
next state. Must never mutate state directly.
• Dispatch — the method to send an action to the store: [Link](action)
• Selector — a function to extract specific data from the store

3. Data Flow (unidirectional)


UI Event (click) -> dispatch(action) -> Reducer -> New State -> Store -> UI re-renders

The flow is strictly one-way. This predictability makes debugging easy.

4. Redux Toolkit (RTK) — Modern Redux


Redux Toolkit is the official, recommended way to write Redux today. It eliminates the boilerplate of classic
Redux.
import { createSlice, configureStore } from '@reduxjs/toolkit';

// Slice — combines actions + reducer in one


const counterSlice = createSlice({
name: 'counter',
initialState: { value: 0 },
reducers: {
increment: (state) => { [Link] += 1; }, // RTK uses Immer — looks like mutation
decrement: (state) => { [Link] -= 1; }, // but produces immutable updates
incrementBy: (state, action) => { [Link] += [Link]; },
},
});

export const { increment, decrement, incrementBy } = [Link];

// Store
const store = configureStore({
reducer: { counter: [Link] },
});

// In a React component
import { useSelector, useDispatch } from 'react-redux';

Page 31
BS CS Web Programming — Complete Study Notes Final Exam Preparation

function Counter() {
const count = useSelector(state => [Link]);
const dispatch = useDispatch();
return (
<div>
<span>{count}</span>
<button onClick={() => dispatch(increment())}>+</button>
</div>
);
}

5. Middleware
Middleware sits between dispatch and the reducer. It can intercept, modify, log, or delay actions. The most
common use case is handling async operations.
// Redux Thunk — the standard middleware for async actions
// Allows dispatching a function instead of an object

export const fetchUser = (userId) => async (dispatch) => {


dispatch({ type: 'user/fetchStart' });
try {
const res = await fetch(`/api/users/${userId}`);
const data = await [Link]();
dispatch({ type: 'user/fetchSuccess', payload: data });
} catch (err) {
dispatch({ type: 'user/fetchError', payload: [Link] });
}
};

// RTK also has createAsyncThunk which handles this automatically


import { createAsyncThunk } from '@reduxjs/toolkit';

export const fetchUser = createAsyncThunk('user/fetch', async (userId) => {


const res = await fetch(`/api/users/${userId}`);
return [Link](); // returned value becomes [Link]
});

6. When to Use Redux (vs local state)


• Use Redux when multiple unrelated components need the same data
• Use Redux when global state changes are complex or frequent
• Use local state (useState) for UI-only state like open/closed modals
• Consider React Context for simple global state that rarely changes
• Redux adds complexity — do not reach for it until you actually need it

7. Common Exam Questions


• What problem does Redux solve that local React state cannot?
• Explain the three principles of Redux.
• What is a reducer? What rules must it follow?
• What is the difference between an action and an action creator?
• What is Redux middleware and what is it used for?
• Explain Redux Thunk and why it is needed.
• Compare Redux vs React Context API for state management.

Page 32
BS CS Web Programming — Complete Study Notes Final Exam Preparation

WEEK 7 — SERVER-SIDE PROGRAMMING WITH


[Link]

Topic 10 · Web Servers, [Link], File System, and Routing

1. What is a Web Server?


A web server is software that listens for HTTP requests on a port and sends back responses. It handles the
entire request-response cycle: receive request, route it to the right handler, process it (run code, query
database), and send back a response.
A static web server (Nginx, Apache) serves files directly. A dynamic web server ([Link], Python Flask, PHP)
runs code to generate responses on the fly.

2. [Link]
[Link] is a JavaScript runtime built on Chrome's V8 engine. It lets you run JavaScript on the server. Key
characteristics:
• Single-threaded but non-blocking through the event loop
• Excellent for I/O-heavy workloads (API servers, real-time apps)
• Not ideal for CPU-intensive tasks (heavy computation blocks the thread)
• NPM (Node Package Manager) — the world's largest package ecosystem
// Minimal HTTP server in pure [Link]
const http = require('http');

const server = [Link]((req, res) => {


[Link](200, { 'Content-Type': 'text/html' });
[Link]('<h1>Hello from [Link]!</h1>');
});

[Link](3000, () => {
[Link]('Server running on [Link]
});

3. [Link] Event Loop (Server Side)


When Node receives a request, it hands off any I/O work (read file, query DB) to the OS and immediately
moves on to the next request. When the I/O completes, the callback is called. This allows one Node process
to handle thousands of concurrent requests without creating a new thread per request.
// Non-blocking I/O example
const fs = require('fs');

// This does NOT block — callback fires when file is read


[Link]('[Link]', 'utf8', (err, data) => {
if (err) throw err;
[Link](data);
});
[Link]('This runs immediately, before the file is read'); // prints first

4. File System Module


const fs = require('fs');
const path = require('path');

Page 33
BS CS Web Programming — Complete Study Notes Final Exam Preparation

// Read file — callback style


[Link]([Link](__dirname, '[Link]'), 'utf8', (err, data) => {
if (err) { [Link](err); return; }
[Link](data);
});

// Write file
[Link]('[Link]', 'Hello!', (err) => {
if (err) throw err;
[Link]('File saved');
});

// Promise-based (modern)
const fsPromises = require('fs').promises;
const data = await [Link]('[Link]', 'utf8');

// Check if file exists


[Link]('[Link]');

// List directory
[Link]('./uploads').forEach(file => [Link](file));

5. Routing (without Express)


const http = require('http');
const url = require('url');

const server = [Link]((req, res) => {


const { pathname, query } = [Link]([Link], true);

if ([Link] === 'GET' && pathname === '/') {


[Link](200, { 'Content-Type': 'text/html' });
[Link]('<h1>Home Page</h1>');
} else if ([Link] === 'GET' && pathname === '/about') {
[Link](200, { 'Content-Type': 'text/html' });
[Link]('<h1>About</h1>');
} else if ([Link] === 'POST' && pathname === '/login') {
// Handle login
[Link](200, { 'Content-Type': 'application/json' });
[Link]([Link]({ success: true }));
} else {
[Link](404);
[Link]('Not Found');
}
});

6. NPM — Package Management


npm init -y # create [Link]
npm install express # install package, adds to dependencies
npm install --save-dev nodemon # dev dependency only
npm install # install all packages from [Link]
npm start # run 'start' script from [Link]
npm run dev # run custom 'dev' script

# [Link] scripts

Page 34
BS CS Web Programming — Complete Study Notes Final Exam Preparation

{
"scripts": {
"start": "node [Link]",
"dev": "nodemon [Link]",
"test": "jest"
}
}

■ node_modules should always be in .gitignore. It can contain hundreds of thousands of files. [Link] and
[Link] are what you commit.

7. Common Exam Questions


• What makes [Link] non-blocking? Explain with the event loop.
• Compare [Link] with Apache/Nginx for serving web content.
• What is the difference between require() and ES6 import?
• What is [Link] and what does it contain?
• What is the difference between dependencies and devDependencies?
• Explain the difference between synchronous and asynchronous file reading in Node.
• What is the __dirname variable in [Link]?

Page 35
BS CS Web Programming — Complete Study Notes Final Exam Preparation

WEEK 8 — STATE MANAGEMENT AND


ARCHITECTURAL PATTERNS

Topic 11 · Cookies, Sessions, and Architectural Patterns

1. Cookies
A cookie is a small piece of data (max 4KB) stored in the browser and sent automatically with every HTTP
request to the matching domain. Cookies solve the statelessness problem of HTTP.
// Server sets a cookie
[Link]('Set-Cookie', 'username=alice; Max-Age=86400; HttpOnly; Secure;
SameSite=Strict');

// Cookie attributes
// Max-Age / Expires — how long the cookie lives. Without it = session cookie (deleted on
browser close)
// HttpOnly — cannot be accessed by JavaScript. Prevents XSS stealing cookies.
// Secure — only sent over HTTPS
// SameSite=Strict — only sent from same site. Prevents CSRF attacks.
// Path — which URLs receive this cookie
// Domain — which domains receive this cookie

Cookie Security Flags Summary


Flag Purpose Why it matters

HttpOnly Blocks JS access to cookie Prevents XSS from stealing session cookie

Secure HTTPS only Prevents sniffing on HTTP connections

SameSite=Strict Same site requests only Prevents CSRF attacks

SameSite=Lax Same site + top-level navigations


Balance between security and usability

2. Sessions
Sessions store user data on the SERVER side. The browser only holds a session ID (in a cookie). When the
browser sends the session ID, the server looks it up to find the user data. This is more secure than storing
data in cookies because sensitive data never leaves the server.
// Express session example
const session = require('express-session');

[Link](session({
secret: 'your-secret-key', // used to sign the session ID cookie
resave: false,
saveUninitialized: false,
cookie: { secure: true, httpOnly: true, maxAge: 1000 * 60 * 60 } // 1 hour
}));

// Login handler
[Link]('/login', (req, res) => {
if (validCredentials([Link])) {
[Link] = [Link]; // store in session
[Link] = [Link];
[Link]('/dashboard');

Page 36
BS CS Web Programming — Complete Study Notes Final Exam Preparation

}
});

// Protected route
[Link]('/dashboard', (req, res) => {
if (![Link]) return [Link]('/login');
[Link]('dashboard', { userId: [Link] });
});

Cookies vs Sessions
Feature Cookies Sessions

Data location Browser (client-side) Server (memory/DB/Redis)

Size limit 4KB No practical limit

Security User can read/modify User only has opaque ID

Scalability Great (no server load) Harder (need shared store for multiple servers)

Persistence Survives browser close Lost on server restart (unless stored in DB)

3. JWT — JSON Web Tokens


JWT is a token-based authentication mechanism. Instead of server-side sessions, the server creates a
signed token and gives it to the client. The client sends it with every request. The server verifies the signature
— no database lookup needed.
JWT structure (three base64-encoded parts separated by dots):
[Link]

Header: { alg: 'HS256', typ: 'JWT' }


Payload: { sub: '123', name: 'Alice', role: 'admin', exp: 1717000000 }
Signature: HMACSHA256(base64(header) + '.' + base64(payload), secret)

// The server verifies the signature on every request


// If the payload were tampered with, the signature would not match

■ JWT payload is base64-encoded, NOT encrypted. Anyone can decode and read the contents. Never store
sensitive information in a JWT. Use HTTPS and sign with a strong secret.

4. MVC Architecture
MVC (Model-View-Controller) is the most common architectural pattern for web applications. It separates
concerns so different parts of the app can evolve independently.
Model — data layer. Database queries, business rules, data validation.
View — presentation layer. Templates, HTML generation, UI.
Controller — logic layer. Receives requests, calls models, passes data to views.

Request Flow:
Browser -> Route -> Controller -> Model (DB) -> Controller -> View -> Response
// Express + MVC structure
// routes/[Link]
[Link]('/users/:id', [Link]);

// controllers/[Link]
[Link] = async (req, res) => {
const user = await [Link]([Link]); // Controller calls Model

Page 37
BS CS Web Programming — Complete Study Notes Final Exam Preparation

[Link]('users/show', { user }); // Controller passes to View


};

// models/[Link]
[Link] = async (id) => {
return [Link]('SELECT * FROM users WHERE id = ?', [id]);
};

5. Hexagonal Architecture (Ports and Adapters)


Also known as Ports and Adapters. The core business logic sits in the centre, isolated from external systems.
External systems (DB, HTTP, UI, email) connect through defined interfaces (ports). This makes the core logic
testable and replaceable — you can swap a MySQL database for MongoDB without touching business logic.
[ HTTP Adapter ] [ CLI Adapter ]
| |
[ Input Ports (interfaces) ]
|
[ CORE BUSINESS LOGIC ]
|
[ Output Ports (interfaces) ]
|
[ DB Adapter ] [ Email Adapter ] [ Cache Adapter ]

6. Other Patterns
• Microservices — split app into small independent services, each with its own DB and deployment.
Communicate via HTTP or message queues.
• Monolith — the entire app as one deployable unit. Simpler to develop initially but harder to scale specific
parts.
• Repository pattern — abstraction layer for data access logic. Keeps DB queries out of controllers.
• Middleware pattern — a chain of functions that each process a request before passing it to the next. Core
to Express.

7. Common Exam Questions


• What is the difference between a cookie and a session?
• What security attributes should be set on a session cookie?
• Explain JWT structure. What are its advantages over sessions?
• Describe the MVC pattern and the role of each component.
• What is the hexagonal architecture and why is it useful?
• What is the difference between monolithic and microservices architecture?
• What happens when a user logs in using session-based authentication?

Page 38
BS CS Web Programming — Complete Study Notes Final Exam Preparation

WEEK 9 — [Link] AND MIDDLEWARE

Topic 12 · [Link]: Framework, Middleware, and REST APIs

1. Overview
Express is a minimal, unopinionated web framework for [Link]. It wraps Node's http module with a cleaner
API for routing, middleware, and request/response handling. It is the most popular [Link] framework and
the foundation of many larger frameworks ([Link], [Link]).

2. Basic Setup
const express = require('express');
const app = express();

// Parse JSON request bodies


[Link]([Link]());

// Parse URL-encoded form data


[Link]([Link]({ extended: true }));

// Routes
[Link]('/', (req, res) => {
[Link]('Hello World');
});

[Link](3000, () => [Link]('Server on port 3000'));

3. Routing
// Route parameters
[Link]('/users/:id', (req, res) => {
const { id } = [Link]; // { id: '42' }
[Link]({ userId: id });
});

// Query strings
[Link]('/search', (req, res) => {
const { q, page = 1 } = [Link]; // /search?q=nodejs&page=2
[Link]({ query: q, page });
});

// Router for modular routes


const userRouter = [Link]();
[Link]('/', [Link]);
[Link]('/:id', [Link]);
[Link]('/', [Link]);
[Link]('/:id', [Link]);
[Link]('/:id', [Link]);
[Link]('/users', userRouter); // prefix all routes with /users

4. Middleware
Middleware functions have access to req, res, and next. They run in a pipeline — each middleware calls
next() to pass to the next one. If next() is never called, the request hangs. Middleware can: modify req/res,
end the request, or pass it along.

Page 39
BS CS Web Programming — Complete Study Notes Final Exam Preparation

// Structure of a middleware function


function myMiddleware(req, res, next) {
[Link](`${[Link]} ${[Link]} at ${new Date().toISOString()}`);
next(); // must call next or the request will hang
}

// Apply globally
[Link](myMiddleware);

// Apply to specific routes


[Link]('/admin', requireAdmin);

// Error handling middleware (MUST have 4 params)


[Link]((err, req, res, next) => {
[Link]([Link]);
[Link](500).json({ error: [Link] });
});

// Common middleware packages


const cors = require('cors'); // Cross-Origin Resource Sharing
const helmet = require('helmet'); // Security headers
const morgan = require('morgan'); // Request logging
const rateLimit = require('express-rate-limit'); // Rate limiting

[Link](cors());
[Link](helmet());
[Link](morgan('dev'));

Middleware Execution Order


Request enters
|
[ Global middleware: morgan, cors, helmet ]
|
[ Body parser: [Link]() ]
|
[ Auth middleware: check JWT / session ]
|
[ Route handler: run business logic ]
|
[ Error handler middleware ]
|
Response sent

5. Building a REST API with Express


// Complete CRUD API for posts
const posts = []; // in-memory store (normally a database)
let nextId = 1;

// GET all posts


[Link]('/api/posts', (req, res) => {
[Link](posts);
});

// GET single post


[Link]('/api/posts/:id', (req, res) => {
const post = [Link](p => [Link] === parseInt([Link]));

Page 40
BS CS Web Programming — Complete Study Notes Final Exam Preparation

if (!post) return [Link](404).json({ error: 'Not found' });


[Link](post);
});

// POST create post


[Link]('/api/posts', (req, res) => {
const { title, body } = [Link];
if (!title || !body) return [Link](400).json({ error: 'Missing fields' });
const post = { id: nextId++, title, body, createdAt: new Date() };
[Link](post);
[Link](201).json(post);
});

// PUT update post


[Link]('/api/posts/:id', (req, res) => {
const idx = [Link](p => [Link] === parseInt([Link]));
if (idx === -1) return [Link](404).json({ error: 'Not found' });
posts[idx] = { ...posts[idx], ...[Link] };
[Link](posts[idx]);
});

// DELETE post
[Link]('/api/posts/:id', (req, res) => {
const idx = [Link](p => [Link] === parseInt([Link]));
if (idx === -1) return [Link](404).json({ error: 'Not found' });
[Link](idx, 1);
[Link](204).send();
});

6. Common Exam Questions


• What is Express middleware? How does the middleware pipeline work?
• What happens if a middleware function does not call next()?
• What is the difference between [Link]() and [Link]()?
• How do you handle errors in Express?
• What are route parameters versus query string parameters?
• What does [Link](201).json(data) do?
• How do you organise routes in a large Express application?

Page 41
BS CS Web Programming — Complete Study Notes Final Exam Preparation

WEEK 10 — TEMPLATE ENGINES

Topic 13 · Template Engines: Pug and Nunjucks

1. What is a Template Engine?


A template engine allows you to embed dynamic data into HTML on the server side before sending it to the
browser. The server renders the template with data, producing a complete HTML page. This is called
Server-Side Rendering (SSR). The browser receives finished HTML — no JavaScript needed to build the
page.
This contrasts with Single-Page Applications (React, Vue) where the browser downloads JS, then JS builds
the HTML. SSR is better for SEO and initial load performance. SPAs are better for interactivity.

2. Pug (formerly Jade)


Pug uses indentation-based syntax (like Python). No closing tags needed. Clean and concise.
//- Pug template: views/[Link]
doctype html
html(lang='en')
head
meta(charset='UTF-8')
title= pageTitle
link(rel='stylesheet', href='/css/[Link]')
body
header
h1 Welcome, #{[Link]}!
main
if [Link]
each post in posts
article
h2= [Link]
p= [Link]
a(href=`/posts/${[Link]}`) Read more
else
p No posts yet.
footer
p &copy; 2025

// Express integration
[Link]('view engine', 'pug');
[Link]('views', './views');

[Link]('/home', async (req, res) => {


const posts = await [Link]();
[Link]('index', {
pageTitle: 'My Blog',
user: [Link],
posts
});
});

3. Nunjucks
Nunjucks is a template language inspired by Jinja2 (Python). It uses familiar HTML with special tags for logic.
Less intimidating than Pug for developers who prefer seeing real HTML.

Page 42
BS CS Web Programming — Complete Study Notes Final Exam Preparation

{# Nunjucks template: views/[Link] #}


<!DOCTYPE html>
<html lang="en">
<head>
<title>{{ pageTitle }}</title>
</head>
<body>
<h1>Welcome, {{ [Link] }}!</h1>

{% for post in posts %}


<article>
<h2>{{ [Link] }}</h2>
<p>{{ [Link] }}</p>
</article>
{% else %}
<p>No posts found.</p>
{% endfor %}

{# Template inheritance #}
{# [Link] defines blocks that child templates fill in #}
</body>
</html>

// Express integration
const nunjucks = require('nunjucks');
[Link]('views', { autoescape: true, express: app });
[Link]('view engine', 'html');

4. Template Inheritance
Both engines support template inheritance — a base template defines a layout with named blocks. Child
templates extend the base and fill in the blocks. This avoids repeating navigation, headers, and footers on
every page.
// [Link]
html
head
title My Site - #{title}
body
include partials/[Link]
main
block content
include partials/[Link]

// [Link] — extends base


extends [Link]
block content
h1 This is the home page
p Some content here.

5. Pug vs Nunjucks
Feature Pug Nunjucks

Syntax Indentation-based, no closing tags HTML with {{ }} and {% %} tags

Learning curve Steeper — looks very different Gentler — still looks like HTML

Page 43
BS CS Web Programming — Complete Study Notes Final Exam Preparation

Feature Pug Nunjucks

Inspiration Haml (Ruby) Jinja2 (Python)

Auto-escaping Yes Yes (configurable)

Whitespace Significant (like Python) Not significant

6. Common Exam Questions


• What is a template engine and what problem does it solve?
• What is the difference between server-side rendering and client-side rendering?
• Explain template inheritance with an example.
• What is auto-escaping and why is it important for security?
• Compare Pug and Nunjucks template engines.
• How does a template engine receive data from an Express route?

Page 44
BS CS Web Programming — Complete Study Notes Final Exam Preparation

WEEK 11 — DATABASES: MONGODB AND MYSQL

Topic 14 · NoSQL (MongoDB) and Relational (MySQL) Databases,


CRUD

1. Relational vs NoSQL Databases


Feature Relational (MySQL) NoSQL (MongoDB)

Data model Tables with rows and columns Collections of JSON documents

Schema Fixed schema — must define columns Flexible — documents can vary

Relationships Foreign keys and JOINs Embedded documents or references

Query language SQL MongoDB query language (JSON-like)

ACID Full ACID compliance Eventually consistent (configurable)

Best for Structured data, complex queries Hierarchical, variable structure data

Scaling Vertical (bigger server) Horizontal (more servers / sharding)

2. MySQL — SQL Fundamentals


-- Create table
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(255) UNIQUE NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- CREATE — insert
INSERT INTO users (name, email) VALUES ('Alice', 'alice@[Link]');

-- READ — select
SELECT * FROM users;
SELECT name, email FROM users WHERE id = 1;
SELECT * FROM users ORDER BY created_at DESC LIMIT 10;
SELECT * FROM users WHERE name LIKE '%ali%';

-- UPDATE
UPDATE users SET name = 'Alice Smith' WHERE id = 1;

-- DELETE
DELETE FROM users WHERE id = 1;

-- JOIN (get posts with their author names)


SELECT [Link], [Link] AS author
FROM posts
INNER JOIN users ON posts.user_id = [Link]
WHERE [Link] = 1
ORDER BY posts.created_at DESC;

Using MySQL with [Link]

Page 45
BS CS Web Programming — Complete Study Notes Final Exam Preparation

const mysql = require('mysql2/promise');

const pool = [Link]({


host: 'localhost', user: 'root', password: 'pass', database: 'myapp'
});

// Always use parameterised queries — never string concatenation


const [rows] = await [Link](
'SELECT * FROM users WHERE email = ?',
[[Link]] // parameter — prevents SQL injection
);

■ NEVER build SQL queries with string concatenation using user input. This opens SQL injection vulnerabilities.
Always use parameterised queries / prepared statements.

3. MongoDB — Document Database


MongoDB stores data as BSON documents (Binary JSON). Data is grouped in collections (like tables). Each
document can have a different structure.
// MongoDB document example
{
_id: ObjectId('507f1f77bcf86cd799439011'),
name: 'Alice',
email: 'alice@[Link]',
address: { // embedded document
street: '123 Main St',
city: 'Lahore'
},
tags: ['admin', 'editor'], // array field
createdAt: ISODate('2024-01-15')
}
// Mongoose with [Link] (ODM — Object Document Mapper)
const mongoose = require('mongoose');

const userSchema = new [Link]({


name: { type: String, required: true },
email: { type: String, required: true, unique: true },
createdAt: { type: Date, default: [Link] }
});
const User = [Link]('User', userSchema);

// CREATE
const user = await [Link]({ name: 'Alice', email: 'alice@[Link]' });

// READ
const users = await [Link](); // all users
const user = await [Link]('507f1f77...'); // by ID
const alice = await [Link]({ email: 'alice@[Link]' });
const admins = await [Link]({ role: 'admin' }).sort({ name: 1 }).limit(10);

// UPDATE
await [Link](id, { name: 'Alice Smith' }, { new: true });

// DELETE
await [Link](id);

// Query operators

Page 46
BS CS Web Programming — Complete Study Notes Final Exam Preparation

[Link]({ age: { $gt: 18, $lt: 65 } }); // greater than 18, less than 65
[Link]({ tags: { $in: ['admin', 'mod'] } }); // tag is in array

4. MongoDB vs MySQL: When to Choose Which


• Choose MySQL when your data is highly structured, has complex relationships, requires transactions (e.g.
banking, e-commerce with inventory)
• Choose MongoDB when your data structure varies across records, you need to store nested/hierarchical
data, or you need to scale horizontally across many servers
• In practice, many large applications use both — relational for transactional data, NoSQL for logs, product
catalogs, or user-generated content

5. Indexes
Indexes make queries fast. Without an index, a query scans every row/document. With an index, it jumps
directly to matching records. The tradeoff: indexes speed up reads but slow down writes and use disk space.
-- MySQL index
CREATE INDEX idx_email ON users(email);

// MongoDB index
await [Link]({ email: 1 }); // 1 = ascending
await [Link]({ createdAt: -1 }); // -1 = descending
await [Link]({ email: 1 }, { unique: true });

6. Common Exam Questions


• What is the difference between SQL and NoSQL databases?
• Explain ACID properties with examples.
• What are the 4 CRUD operations? Give SQL and MongoDB examples of each.
• What is a JOIN in SQL? When would you use LEFT vs INNER JOIN?
• What is an index and what is the tradeoff of adding one?
• What is SQL injection and how do parameterised queries prevent it?
• When would you embed a document vs reference another document in MongoDB?
• What is an ODM? How does Mongoose relate to MongoDB?

Page 47
BS CS Web Programming — Complete Study Notes Final Exam Preparation

WEEK 12 — OVERVIEW OF OTHER SERVER-SIDE


FRAMEWORKS

Topic 15 · Django, Laravel, Ruby on Rails, and Framework


Comparison

1. Why Learn Multiple Frameworks?


Different frameworks make different tradeoffs. Knowing the landscape means you can pick the right tool for a
project and understand concepts that transfer across frameworks (routing, middleware, ORM, templating).

2. Django (Python)
• Full-stack framework with 'batteries included' — ORM, admin panel, auth, forms, templating all built in
• MVT (Model-View-Template) architecture — similar to MVC, just named differently
• Excellent for data-heavy apps, content management systems, and rapid prototyping
• Strong security defaults — CSRF protection, SQL injection prevention, XSS escaping all on by default
# Django view example
from [Link] import render
from .models import Post

def post_list(request):
posts = [Link](published=True).order_by('-created_at')
return render(request, 'blog/post_list.html', {'posts': posts})

3. Laravel (PHP)
• Most popular PHP framework — elegant syntax, rich ecosystem
• Full-stack with Eloquent ORM, Blade templates, built-in authentication, queues, caching
• Artisan CLI for generating boilerplate code
• Powers many WordPress-adjacent and traditional web apps
// Laravel route and controller
Route::get('/posts', [PostController::class, 'index']);

class PostController extends Controller {


public function index() {
$posts = Post::where('published', true)->latest()->get();
return view('[Link]', compact('posts'));
}
}

4. Ruby on Rails
• Convention over Configuration — if you follow naming conventions, Rails wires everything automatically
• Don't Repeat Yourself (DRY) — scaffolding generates CRUD boilerplate instantly
• Active Record ORM — the model layer is powerful and expressive
• Popularised REST in web development. Influenced Express, Laravel, and Django deeply.

5. Framework Comparison
Framework Language Philosophy Best for

Express [Link] Minimal, unopinionated APIs, microservices, real-time

Page 48
BS CS Web Programming — Complete Study Notes Final Exam Preparation

Framework Language Philosophy Best for

Django Python Batteries included, rapid dev Data-heavy apps, admin tools

Laravel PHP Elegant, full-stack Traditional web, CMSs

Rails Ruby Convention over config Rapid prototyping, startups

Spring Java Enterprise-grade Large-scale enterprise apps

[Link] C# Microsoft ecosystem Enterprise Windows environments

NestJS [Link] Angular-like, TypeScript Enterprise Node APIs

6. Common Exam Questions


• What is the difference between a minimal framework (Express) and a full-stack framework (Django)?
• What does 'convention over configuration' mean in Ruby on Rails?
• What are the advantages of Django's built-in admin panel?
• Compare any two server-side frameworks on at least four dimensions.
• What is an ORM and what problem does it solve?

Page 49
BS CS Web Programming — Complete Study Notes Final Exam Preparation

WEEK 13 — WEB SERVICES: SOA AND RESTFUL


APIS

Topic 16 · SOA, REST, and RESTful API Design

1. Service-Oriented Architecture (SOA)


SOA is an architectural style where a system is built from a collection of services that communicate over a
network. Each service is a black box that exposes a well-defined interface. Services can be written in
different languages and replaced independently.
Traditional SOA used SOAP (Simple Object Access Protocol) — XML-based, strict contracts (WSDL files),
heavyweight. REST replaced SOAP for most modern web services.

2. SOAP vs REST
Feature SOAP REST

Protocol XML over HTTP/SMTP/TCP HTTP only

Message XML JSON (usually)

Contract WSDL (strict) API documentation (flexible)

Overhead High (verbose XML) Low (compact JSON)

Caching Not built-in Built into HTTP

Transactions Built-in (WS-AtomicTx) Handle at application level

Used in Legacy banking, enterprise Modern web APIs, mobile backends

3. REST — Representational State Transfer


REST is an architectural style (not a protocol) defined by Roy Fielding in his 2000 dissertation. A service that
follows REST constraints is called RESTful.

The 6 REST constraints


• Client-Server — client and server are separate; client does not know how data is stored
• Stateless — every request contains all information needed; server stores no session
• Cacheable — responses must state if they can be cached or not
• Uniform Interface — consistent URLs, HTTP methods, and representations
• Layered System — client cannot tell if it is connected directly to the server or via proxies
• Code on Demand (optional) — server can send executable code to the client

4. RESTful API Design


Resources are nouns, HTTP methods are verbs. Never put verbs in URLs.
// Resource: /users
GET /users List all users
POST /users Create a new user
GET /users/:id Get user with id
PUT /users/:id Replace user entirely
PATCH /users/:id Update user partially
DELETE /users/:id Delete user

Page 50
BS CS Web Programming — Complete Study Notes Final Exam Preparation

// Nested resources
GET /users/:id/posts Get all posts by a specific user
POST /users/:id/posts Create a post for a specific user

// BAD URLs — verbs in URL


GET /getUsers // wrong
POST /createUser // wrong
GET /deleteUser/5 // wrong and dangerous (GET should never cause side effects)

Response format best practices


// Consistent JSON response envelope
{
'status': 'success',
'data': { ... },
'message': 'User created successfully'
}

// Error response
{
'status': 'error',
'error': {
'code': 'VALIDATION_ERROR',
'message': 'Email is required',
'field': 'email'
}
}

5. GraphQL vs REST
GraphQL is an alternative to REST developed by Facebook. With REST, the server decides what data is in
each response. With GraphQL, the client specifies exactly what fields it needs.
• REST: multiple endpoints, fixed responses. May over-fetch (too much data) or under-fetch (need multiple
requests).
• GraphQL: single endpoint (/graphql). Client queries exactly the fields it needs. Reduces
over/under-fetching.
• REST is simpler to implement and widely understood. GraphQL shines in complex UIs with many data
relationships.

6. API Versioning
// Option 1: URL versioning (most common)
GET /api/v1/users
GET /api/v2/users

// Option 2: Header versioning


GET /api/users
Accept: application/[Link].v2+json

// Option 3: Query parameter


GET /api/users?version=2

7. Common Exam Questions


• What does REST stand for? What are its 6 architectural constraints?
• Why should HTTP verbs not appear in REST API URLs?
• What is the difference between PUT and PATCH?

Page 51
BS CS Web Programming — Complete Study Notes Final Exam Preparation

• Compare REST and SOAP. When would you still choose SOAP?
• What is the difference between REST and GraphQL?
• What HTTP status code should a successful POST that creates a resource return?
• What is API versioning and why is it important?
• What does it mean for an HTTP method to be idempotent?

Page 52
BS CS Web Programming — Complete Study Notes Final Exam Preparation

WEEK 14 — DEPLOYMENT, HOSTING, AND


SECURITY (SSL/TLS)

Topic 17 · Deployment, Nginx/Apache, Cloud, SSL, and Digital


Certificates

1. Web Server Software: Nginx vs Apache


Feature Nginx Apache

Architecture Event-driven, async Process/thread per connection

Performance Excellent under high load Good, heavier under load

Config format Declarative ([Link]) Directive-based (.htaccess)

Dynamic content Needs FastCGI/proxy Built-in modules (mod_php)

Static files Extremely fast Good

Best use Reverse proxy, load balancer, staticShared


contenthosting, .htaccess flexibility

Nginx as Reverse Proxy for [Link]


# /etc/nginx/sites-available/myapp
server {
listen 80;
server_name [Link] [Link];

# Redirect HTTP to HTTPS


return 301 [Link]
}

server {
listen 443 ssl;
server_name [Link];

ssl_certificate /etc/letsencrypt/live/[Link]/[Link];
ssl_certificate_key /etc/letsencrypt/live/[Link]/[Link];

location / {
proxy_pass [Link] # forward to [Link]
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}

# Serve static files directly (faster)


location /static/ {
root /var/www/myapp/public;
}
}

Page 53
BS CS Web Programming — Complete Study Notes Final Exam Preparation

2. Deployment Concepts
• VPS (Virtual Private Server) — a virtual machine on shared hardware. Full control. Examples:
DigitalOcean Droplet, AWS EC2, Linode.
• PaaS (Platform as a Service) — deploy your code, the platform handles servers. Examples: Heroku,
Railway, Render, Vercel.
• Serverless — run functions in response to events, no server management. Examples: AWS Lambda,
Cloudflare Workers, Vercel Functions.
• Containers (Docker) — package app + dependencies into a portable image. Kubernetes orchestrates
many containers.
• CDN (Content Delivery Network) — serve static assets from servers close to the user. Examples:
Cloudflare, AWS CloudFront.

3. Environment Variables and Configuration


# .env file (never commit to Git)
DB_HOST=localhost
DB_PASSWORD=supersecret
JWT_SECRET=my-very-long-random-secret
NODE_ENV=production
PORT=3000

// [Link] with dotenv


require('dotenv').config();
const dbPassword = [Link].DB_PASSWORD;

■ .env files must ALWAYS be in .gitignore. Pushing secrets to GitHub is a critical security incident.

4. SSL/TLS and HTTPS


SSL (Secure Sockets Layer) was the original protocol; TLS (Transport Layer Security) is its modern
replacement. Everyone still says 'SSL' colloquially but TLS 1.2/1.3 is what is actually used.

TLS Handshake
1. Client Hello — browser says which TLS version and cipher suites it supports
2. Server Hello — server chooses TLS version and cipher suite
3. Certificate — server sends its digital certificate (public key + identity)
4. Key Exchange — both sides agree on a session key (using asymmetric crypto)
5. Finished — all subsequent communication uses the session key (symmetric crypto)

5. Digital Certificates and PKI


A digital certificate binds a public key to an identity (domain name, organisation). It is issued and signed by a
Certificate Authority (CA) — a trusted third party like Let's Encrypt, DigiCert, or Comodo.
Certificate contains:
- Domain name (Subject / CN)
- Public key of the domain
- Issuing CA name
- Validity period (not before / not after)
- CA's digital signature

When browser receives certificate:


1. Check if domain matches certificate Subject
2. Check if certificate is expired
3. Check if issuing CA is in browser's trust store
4. Verify CA's signature on the certificate

Page 54
BS CS Web Programming — Complete Study Notes Final Exam Preparation

• Let's Encrypt — free, automated CA. Powers most of the web's HTTPS. Certificates last 90 days and
auto-renew.
• Self-signed certificates — signed by yourself, not a CA. Browsers show a warning. Only for
development/internal tools.

Types of Certificates
• DV (Domain Validated) — proves domain ownership. Fast and free (Let's Encrypt).
• OV (Organisation Validated) — verifies the organisation exists. Shows org name in cert.
• EV (Extended Validation) — thorough vetting. Shows company name in browser address bar. Used by
banks.

6. Common Exam Questions


• What is the difference between Nginx and Apache? When would you choose each?
• What is a reverse proxy and why is [Link] typically put behind one?
• Describe the TLS handshake step by step.
• What is a digital certificate and what does it contain?
• What is a Certificate Authority and why does trust in them matter?
• What is the difference between SSL and TLS?
• What is a CDN and how does it improve performance?
• What is the difference between VPS, PaaS, and serverless deployment?

Page 55
BS CS Web Programming — Complete Study Notes Final Exam Preparation

WEEK 15 — SECURITY ATTACKS, PERFORMANCE,


AND HTTP/2-3

Topic 18 · XSS, CSRF, Cross-Domain, Performance, SSR, HTTP/2 &


HTTP/3

1. Cross-Site Scripting (XSS)


XSS is an attack where malicious JavaScript is injected into a web page and executed in the victim's
browser. The attacker's script runs with the same privileges as the page, allowing it to steal cookies, session
tokens, or redirect users.

Types of XSS
• Stored XSS — malicious script is saved to the database (e.g. in a forum post) and executed every time
anyone views it
• Reflected XSS — malicious script is in the URL parameter, server reflects it back in the response
• DOM-based XSS — malicious script is injected through client-side JavaScript without touching the server
// XSS attack example
// Attacker posts this as a comment:
<script>[Link]='[Link]

// When the page displays this comment without escaping:


// The script runs and sends the victim's cookies to [Link]

// PREVENTION
// 1. Always escape user input before displaying it
const safe = htmlEncode(userInput);
// htmlEncode converts < to &lt;, > to &gt;, etc.

// 2. Content Security Policy (CSP) header


[Link]('Content-Security-Policy',
"default-src 'self'; script-src 'self'; style-src 'self'");
// This tells the browser to only execute scripts from your own domain

// 3. NEVER use innerHTML with user data — use textContent


[Link] = userInput; // safe
[Link] = userInput; // DANGEROUS

2. Cross-Site Request Forgery (CSRF)


CSRF tricks a victim's browser into making an authenticated request to a site the victim is logged into. The
victim does not know it is happening. The server thinks it is a legitimate request because it comes with the
victim's session cookie.
// Attack scenario
// 1. Victim is logged into [Link] (has session cookie)
// 2. Victim visits [Link] which contains:
<img src='[Link] />
// 3. Victim's browser sends the request WITH their [Link] cookie
// 4. Bank processes the transfer

// PREVENTION
// CSRF Token — server puts a secret random token in forms

Page 56
BS CS Web Programming — Complete Study Notes Final Exam Preparation

// Server validates token on every state-changing request


<form method='POST' action='/transfer'>
<input type='hidden' name='_csrf' value='e9a8f3...' />
...
</form>

// SameSite=Strict cookie prevents cookies from being sent


// on cross-site requests entirely

3. Cross-Domain Issues and CORS


The Same-Origin Policy (SOP) is a browser security rule: JavaScript on one origin (domain + port + protocol)
cannot read responses from a different origin. CORS (Cross-Origin Resource Sharing) is the mechanism that
allows servers to selectively allow cross-origin requests.
// A request from [Link] to [Link]
// is cross-origin — blocked by default unless [Link]
// sends the right CORS headers

// Express CORS setup


const cors = require('cors');

// Allow all origins (only for public APIs)


[Link](cors());

// Restrict to specific origins (production)


[Link](cors({
origin: ['[Link] '[Link]
methods: ['GET', 'POST', 'PUT', 'DELETE'],
credentials: true, // allow cookies
allowedHeaders: ['Content-Type', 'Authorization']
}));

// Resulting response headers:


// Access-Control-Allow-Origin: [Link]
// Access-Control-Allow-Credentials: true

Preflight Requests
Before sending certain cross-origin requests (POST with JSON, requests with custom headers), the browser
first sends an OPTIONS request to ask the server if the real request is allowed. The server must respond
with the correct CORS headers or the real request is blocked.

4. SQL Injection (brief recap)


// Vulnerable code
const query = `SELECT * FROM users WHERE email = '${[Link]}'`;
// If attacker enters: ' OR 1=1 --
// Query becomes: SELECT * FROM users WHERE email = '' OR 1=1 --'
// Returns ALL users

// Safe — parameterised query


const [rows] = await [Link]('SELECT * FROM users WHERE email = ?', [[Link]]);

5. Web Performance
Key performance metrics
• TTFB (Time to First Byte) — how long until the browser receives the first byte of the response

Page 57
BS CS Web Programming — Complete Study Notes Final Exam Preparation

• FCP (First Contentful Paint) — when first text or image appears


• LCP (Largest Contentful Paint) — when the largest visible element loads
• CLS (Cumulative Layout Shift) — how much the page jumps around during load
• TTI (Time to Interactive) — when the page becomes fully interactive

Performance techniques
• Minification — remove whitespace, comments, and shorten variable names in JS/CSS
• Compression — Gzip or Brotli compress HTTP responses (60-80% size reduction)
• Caching — set Cache-Control headers for static assets
• Code splitting — split JS bundle so you only load code needed for the current page
• Lazy loading — images and components load only when they enter the viewport
• CDN — serve static assets from geographically close edge nodes
• Database indexes — ensure slow queries are optimised
• HTTP/2 — multiplexing eliminates head-of-line blocking

6. Server-Side Rendering (SSR)


With CSR (Client-Side Rendering), the browser downloads a minimal HTML shell, downloads JS, runs JS to
build the page. This is slow on first load and bad for SEO because crawlers may not run JavaScript. SSR
generates the complete HTML on the server first.
• [Link] (React SSR) — getServerSideProps() renders the page on the server per request
• Static Site Generation (SSG) — pages are pre-rendered at build time. Fastest possible TTFB.
• Incremental Static Regeneration (ISR) — pre-render, but regenerate in the background periodically

7. HTTP/2 and HTTP/3


• HTTP/2 over TCP: multiplexing (multiple requests over one connection), header compression (HPACK),
server push (proactively send resources), binary framing (not plain text)
• HTTP/2 problem: TCP head-of-line blocking. If one packet is lost, all streams on that connection wait.
• HTTP/3 over QUIC (UDP-based): fixes TCP head-of-line blocking, 0-RTT connection resumption, built-in
TLS 1.3, independent streams
HTTP/1.1: request1 -> wait -> request2 -> wait -> request3
HTTP/2: request1 ----+----
request2 ----|---- all multiplexed on one TCP connection
request3 ----+----
HTTP/3: Same as HTTP/2 but over QUIC — no head-of-line blocking between streams

8. Security Headers Summary


Header What it does

Content-Security-Policy Controls which resources can be loaded. Prevents XSS.

X-Frame-Options: DENY Prevents page from being embedded in an iframe. Prevents clickjacking.

Strict-Transport-Security (HSTS) Forces browser to use HTTPS for future visits. Prevents downgrade attacks.

X-Content-Type-Options: nosniff Prevents browser from MIME-sniffing. Prevents content-type attacks.

Referrer-Policy Controls how much referrer info is sent with requests.

9. Common Exam Questions


• Explain XSS. What are the three types and how do you prevent each?
• What is CSRF and how do CSRF tokens prevent it?
• What is CORS? What is the Same-Origin Policy?

Page 58
BS CS Web Programming — Complete Study Notes Final Exam Preparation

• What is a preflight request?


• What is the Content Security Policy header and how does it prevent XSS?
• What is HSTS and why is it important?
• Compare HTTP/2 and HTTP/3. What problem does HTTP/3 solve?
• What is the difference between SSR and CSR? When is each preferred?
• List five techniques to improve web application performance.

Page 59
BS CS Web Programming — Complete Study Notes Final Exam Preparation

WEEK 16 — EMERGING TRENDS

Topic 19 · WebSockets, WebAssembly, and Progressive Web Apps

1. WebSockets
HTTP is a request-response protocol — the client always initiates. WebSockets provide a persistent,
full-duplex (two-way) communication channel over a single TCP connection. The server can push data to the
client at any time without the client asking.

Use cases
• Real-time chat applications (WhatsApp Web, Slack)
• Live notifications
• Collaborative editing (Google Docs)
• Live sports scores
• Multiplayer games
• Financial market data feeds

WebSocket handshake
// WebSocket starts as an HTTP request then upgrades
GET /chat HTTP/1.1
Host: [Link]
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==

// Server responds
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
// After this, connection is a persistent WebSocket — no more HTTP
// Browser WebSocket API
const ws = new WebSocket('[Link]

[Link] = () => {
[Link]('Connected');
[Link]([Link]({ type: 'join', room: 'general' }));
};

[Link] = (event) => {


const msg = [Link]([Link]);
displayMessage(msg);
};

[Link] = () => [Link]('Disconnected');


[Link] = (err) => [Link](err);

// Server with [Link] ([Link])


const io = require('[Link]')(server);

[Link]('connection', (socket) => {


[Link]('User connected:', [Link]);

Page 60
BS CS Web Programming — Complete Study Notes Final Exam Preparation

[Link]('message', (data) => {


[Link]('message', data); // broadcast to ALL clients
});

[Link]('disconnect', () => [Link]('User left'));


});

HTTP Polling vs WebSockets


• Short polling — client asks 'anything new?' every N seconds. Wasteful.
• Long polling — client asks, server holds the connection open until it has data to send, then client
immediately asks again. Hacky.
• Server-Sent Events (SSE) — server pushes to client over HTTP. One direction only. Good for
notifications/feeds.
• WebSockets — true bidirectional. Best for real-time interaction.

2. WebAssembly (WASM)
WebAssembly is a binary instruction format that runs in the browser at near-native speed. It is not a
replacement for JavaScript — it is a compilation target for languages like C, C++, Rust, and Go that need
high performance in the browser.

Use cases
• Video/audio editing in the browser (Adobe Premiere Web uses WASM)
• Games — 3D game engines compiled to WASM
• Scientific computing and simulations
• Encryption and cryptography — faster than JS
• Figma, AutoCAD Web, Google Earth — all use WASM
// Using a WASM module in JavaScript
const response = await fetch('[Link]');
const buffer = await [Link]();
const { instance } = await [Link](buffer);

// Call the exported function from WASM


const result = [Link](imageData, width, height);
[Link]('Processing done, result:', result);

JavaScript vs WebAssembly
Feature JavaScript WebAssembly

Written in JavaScript C, C++, Rust, Go (compiled)

Format Text Binary

Performance Fast (JIT compiled) Near-native

DOM access Direct Via JavaScript bridge

Use case UI, logic, interactivity CPU-intensive computation

Debugging Excellent tooling More complex

3. Progressive Web Applications (PWAs)


A Progressive Web App is a web application that uses modern web APIs to provide an experience similar to
a native mobile or desktop app. The user can install it to their home screen, use it offline, and receive push
notifications — all without going through an app store.

Page 61
BS CS Web Programming — Complete Study Notes Final Exam Preparation

PWA requirements
• HTTPS — PWAs only work on secure origins
• Web App Manifest — a JSON file describing the app (name, icons, theme color, display mode)
• Service Worker — a JavaScript file that runs in the background, intercepts network requests, and can
serve cached responses even offline

Web App Manifest


// [Link]
{
"name": "My Weather App",
"short_name": "Weather",
"description": "Real-time weather for your city",
"start_url": "/",
"display": "standalone", // hides browser UI
"background_color": "#1B4F8A",
"theme_color": "#0D1B2A",
"icons": [
{ "src": "/icons/[Link]", "sizes": "192x192", "type": "image/png" },
{ "src": "/icons/[Link]", "sizes": "512x512", "type": "image/png" }
]
}

Service Worker — Caching Strategy


// [Link]
const CACHE_NAME = 'my-app-v1';
const ASSETS = ['/', '/[Link]', '/css/[Link]', '/js/[Link]'];

// Install — cache static assets


[Link]('install', (event) => {
[Link](
[Link](CACHE_NAME).then(cache => [Link](ASSETS))
);
});

// Fetch — serve from cache, fall back to network


[Link]('fetch', (event) => {
[Link](
[Link]([Link]).then(cached => {
return cached || fetch([Link]).then(response => {
// Optionally cache the new response
const clone = [Link]();
[Link](CACHE_NAME).then(cache => [Link]([Link], clone));
return response;
});
})
);
});

// Register service worker in your main app JS


if ('serviceWorker' in navigator) {
[Link]('/[Link]');
}

Caching strategies

Page 62
BS CS Web Programming — Complete Study Notes Final Exam Preparation

Strategy Behaviour Best for

Cache First Serve from cache, fall back to network


Static assets (CSS, fonts)

Network First Try network, fall back to cache Dynamic content that should be fresh

Stale While Revalidate Serve cache immediately, update inBalance


background
freshness and speed

Cache Only Only serve from cache Pre-cached app shell

Network Only Always go to network Non-cacheable (analytics, payments)

4. Push Notifications in PWAs


Service workers can receive push messages from a server even when the PWA is not open. The browser
shows a native-style notification. This uses the Push API (browser) and a push service (Google FCM, Mozilla
Autopush).

5. Common Exam Questions


• What is the difference between HTTP polling, Server-Sent Events, and WebSockets?
• Describe the WebSocket handshake process.
• What is WebAssembly and what types of tasks is it suited for?
• What are the three technical requirements for a PWA?
• What is a Service Worker and what can it do?
• Explain the 'Cache First' vs 'Network First' caching strategies.
• What is a Web App Manifest?
• Compare native apps vs PWAs. What can each do that the other cannot?
• How does WebAssembly interact with JavaScript in a browser?

6. Common Mistakes
■ Thinking WebSockets replace HTTP — they are for persistent real-time communication. Regular page loads
and REST APIs still use HTTP.
■ Thinking WebAssembly replaces JavaScript — it complements JS for specific performance-critical tasks. JS
still handles the DOM.
■ Forgetting HTTPS is required for Service Workers and PWAs. They will not work on HTTP.
■ Caching too aggressively with Service Workers can cause users to see stale content for a long time. Have a
clear cache versioning and invalidation strategy.

Page 63
BS CS Web Programming — Complete Study Notes Final Exam Preparation

QUICK REFERENCE — EXAM CHEAT SHEETS

HTTP Status Codes Reference


Code Name When to return it

200 OK Successful GET / PUT / PATCH

201 Created Successful POST that created a resource

204 No Content Successful DELETE (no body returned)

301 Moved Permanently URL has permanently changed (SEO-safe redirect)

302 Found Temporary redirect

304 Not Modified Resource unchanged — serve from cache

400 Bad Request Client sent invalid data / validation error

401 Unauthorized Not authenticated — must log in first

403 Forbidden Authenticated but not allowed to access this resource

404 Not Found Resource does not exist

409 Conflict Duplicate resource (e.g. email already registered)

422 Unprocessable Entity Request body is syntactically valid but semantically wrong

429 Too Many Requests Rate limit exceeded

500 Internal Server Error Unhandled exception on the server

502 Bad Gateway Proxy received invalid response from upstream server

503 Service Unavailable Server is down or overloaded

Key Web Security Summary


Attack What it is Primary Defence

XSS Inject JS into page via user content Escape output, CSP header

CSRF Trick browser to make authenticatedCSRF


request
tokens, SameSite cookies

SQL Injection Inject SQL via input fields Parameterised queries

MITM Intercept traffic on the network HTTPS, HSTS

Clickjacking Embed your page in an iframe to trick


X-Frame-Options:
clicks DENY

IDOR Access resources by guessing IDs Authorise every request server-side

Brute Force Try many passwords Rate limiting, account lockout

Technology Stack Overview

Page 64
BS CS Web Programming — Complete Study Notes Final Exam Preparation

Layer Technologies Purpose

Browser Chrome, Firefox, Safari Render HTML/CSS/JS

Frontend HTML, CSS, JS, React, Redux User interface and interactivity

CSS Framework Bootstrap, Tailwind Styling utilities and components

HTTP HTTP/1.1, HTTP/2, HTTP/3 Client-server communication

Web Server Nginx, Apache Handle requests, serve files, reverse proxy

App Server [Link] + Express Business logic, routing, APIs

Template Pug, Nunjucks Server-side HTML rendering

Auth Sessions + cookies, JWT User identity and access

Database MongoDB, MySQL Persist data

Cloud AWS, GCP, DigitalOcean Hosting and infrastructure

Security TLS, CSP, CSRF tokens Protect data and users

Real-time WebSockets, [Link] Push events to client

Performance CDN, compression, HTTP/2, SSR Fast page delivery

Page 65
BS CS Web Programming — Complete Study Notes Final Exam Preparation

Glossary of Key Terms


ACID Atomicity, Consistency, Isolation, Durability — properties of reliable database transactions

API Application Programming Interface — a contract between two software systems

BSON Binary JSON — the format MongoDB stores documents in

CDN Content Delivery Network — servers at edge locations that cache and serve content

CORS Cross-Origin Resource Sharing — mechanism to allow/deny cross-origin HTTP requests

CSRF Cross-Site Request Forgery — attack using victim's authenticated session

CSP Content Security Policy — header that restricts what resources a page can load

DOM Document Object Model — browser's in-memory tree representation of an HTML document

FCP First Contentful Paint — performance metric for when first content appears

HSTS HTTP Strict Transport Security — forces browsers to use HTTPS

HTTP HyperText Transfer Protocol — stateless application protocol for the web

HTTPS HTTP over TLS — encrypted version of HTTP

JWT JSON Web Token — signed token for stateless authentication

LCP Largest Contentful Paint — main performance/SEO metric

MVC Model-View-Controller — architectural pattern separating data, logic, and presentation

npm Node Package Manager — package manager and registry for [Link]

ORM/ODM Object-Relational/Document Mapper — library mapping objects to DB rows/documents

PWA Progressive Web App — web app with native-like capabilities

REST Representational State Transfer — architectural style for HTTP APIs

SOP Same-Origin Policy — browser security rule blocking cross-origin JS reads

SQL Structured Query Language — language for relational database operations

SSR Server-Side Rendering — generating complete HTML on the server before sending to browser

TCP Transmission Control Protocol — reliable, ordered transport protocol

TLS Transport Layer Security — cryptographic protocol providing HTTPS

TTL Time To Live — how long a cached value is considered valid

WASM WebAssembly — binary format for near-native performance in the browser

XSS Cross-Site Scripting — attack injecting malicious JS into a web page

Page 66

You might also like