WebProgramming StudyNotes
WebProgramming StudyNotes
BS Computer Science
Web Programming
Complete Study Notes
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
Page 1
BS CS Web Programming — Complete Study Notes Final Exam Preparation
TABLE OF CONTENTS
Week Area Topics Covered
Week 2 Client-Side: CSS Selectors · Box Model · Responsive Design · Bootstrap / Tailwind
Week 4 DOM & jQuery DOM Manipulation · Events · jQuery · Client-Side Frameworks Overview
Week 9 Express & Middleware Express Intro · Middleware · REST with Express
Page 2
BS CS Web Programming — Complete Study Notes Final Exam Preparation
WEEK 1 — FOUNDATIONS
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).
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)
3. URL Structure
Page 3
BS CS Web Programming — Complete Study Notes Final Exam Preparation
[Link]
■ The fragment (#) is NEVER sent to the server. This is a classic exam trap.
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.
6. Common Ports
Port Protocol / Service
80 HTTP
443 HTTPS
21 FTP
22 SSH
25 SMTP (email)
3306 MySQL
27017 MongoDB
Page 4
BS CS Web Programming — Complete Study Notes Final Exam Preparation
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
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.
<!DOCTYPE html>
<html>...</html>
4. HTTP Methods
Method Purpose Has Body? Idempotent Safe?
?
✓ Idempotent: calling it multiple times has the same effect as calling it once. Safe: does not modify data.
Page 6
BS CS Web Programming — Complete Study Notes Final Exam Preparation
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
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
Page 7
BS CS Web Programming — Complete Study Notes Final Exam Preparation
Page 8
BS CS Web Programming — Complete Study Notes Final Exam Preparation
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>
Element Purpose
Page 9
BS CS Web Programming — Complete Study Notes Final Exam Preparation
Element Purpose
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>
<button type="submit">Login</button>
</form>
Page 10
BS CS Web Programming — Complete Study Notes Final Exam Preparation
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
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.
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. *
■ !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; }
Page 12
BS CS Web Programming — Complete Study Notes Final Exam Preparation
| | | +----------------+ | | |
| | | | CONTENT | | | | <- Where text/images go
| | | +----------------+ | | |
| | +----------------------+ | |
| +----------------------------+ |
+----------------------------------+
5. Display Property
Value Behaviour
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 */
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 */
}
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
Media Queries
/* Mobile-first approach — base styles for small screens */
.container { width: 100%; padding: 16px; }
/* 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">
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>
Learning curve Low — quick to start Medium — need to learn utility classes
Bundle size Larger (unused CSS included) Very small with purge/JIT
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 */
}
Page 17
BS CS Web Programming — Complete Study Notes Final Exam Preparation
Page 18
BS CS Web Programming — Complete Study Notes Final Exam Preparation
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.
Re-declare Yes No No
4. Functions
// Function declaration (hoisted)
function add(a, b) { return a + b; }
Page 19
BS CS Web Programming — Complete Study Notes Final Exam Preparation
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)
Page 20
BS CS Web Programming — Complete Study Notes Final Exam Preparation
Destructuring
const [first, second, ...rest] = [1, 2, 3, 4, 5];
const { a, b: renamed, c = 'default' } = { a: 1, b: 2 };
// [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
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;
};
}
[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
}
// Generics
function first<T>(arr: T[]): T | undefined {
return arr[0];
}
Page 22
BS CS Web Programming — Complete Study Notes Final Exam Preparation
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
Page 23
BS CS Web Programming — Complete Study Notes Final Exam Preparation
2. Selecting Elements
// Modern selectors (preferred)
[Link]('#header'); // returns first match (CSS selector)
[Link]('.card'); // returns NodeList of all matches
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';
Page 24
BS CS Web Programming — Complete Study Notes Final Exam Preparation
4. Events
const btn = [Link]('#submit-btn');
// Common events
// click, dblclick, mouseover, mouseout, mousedown, mouseup
// keydown, keyup, keypress
// submit, change, input, focus, blur
// scroll, resize, load, DOMContentLoaded
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
Page 26
BS CS Web Programming — Complete Study Notes Final Exam Preparation
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>;
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>
);
}
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" />
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';
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);
});
✓ Dependency array rules: [] = run once on mount. [x] = run when x changes. No array = run after every render
(usually wrong).
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.
■ 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.
Page 30
BS CS Web Programming — Complete Study Notes Final Exam Preparation
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
// 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
Page 32
BS CS Web Programming — Complete Study Notes Final Exam Preparation
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');
[Link](3000, () => {
[Link]('Server running on [Link]
});
Page 33
BS CS Web Programming — Complete Study Notes Final Exam Preparation
// 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');
// List directory
[Link]('./uploads').forEach(file => [Link](file));
# [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.
Page 35
BS CS Web Programming — Complete Study Notes Final Exam Preparation
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
HttpOnly Blocks JS access to cookie Prevents XSS from stealing session cookie
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
Scalability Great (no server load) Harder (need shared store for multiple servers)
Persistence Survives browser close Lost on server restart (unless stored in DB)
■ 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
// models/[Link]
[Link] = async (id) => {
return [Link]('SELECT * FROM users WHERE id = ?', [id]);
};
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.
Page 38
BS CS Web Programming — Complete Study Notes Final Exam Preparation
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();
// Routes
[Link]('/', (req, res) => {
[Link]('Hello World');
});
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 });
});
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
// Apply globally
[Link](myMiddleware);
[Link](cors());
[Link](helmet());
[Link](morgan('dev'));
Page 40
BS CS Web Programming — Complete Study Notes Final Exam Preparation
// 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();
});
Page 41
BS CS Web Programming — Complete Study Notes Final Exam Preparation
// Express integration
[Link]('view engine', 'pug');
[Link]('views', './views');
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
{# 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]
5. Pug vs Nunjucks
Feature Pug Nunjucks
Learning curve Steeper — looks very different Gentler — still looks like HTML
Page 43
BS CS Web Programming — Complete Study Notes Final Exam Preparation
Page 44
BS CS Web Programming — Complete Study Notes Final Exam Preparation
Data model Tables with rows and columns Collections of JSON documents
Schema Fixed schema — must define columns Flexible — documents can vary
Best for Structured data, complex queries Hierarchical, variable structure data
-- 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;
Page 45
BS CS Web Programming — Complete Study Notes Final Exam Preparation
■ NEVER build SQL queries with string concatenation using user input. This opens SQL injection vulnerabilities.
Always use parameterised queries / prepared statements.
// 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
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 });
Page 47
BS CS Web Programming — Complete Study Notes Final Exam Preparation
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']);
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
Page 48
BS CS Web Programming — Complete Study Notes Final Exam Preparation
Django Python Batteries included, rapid dev Data-heavy apps, admin tools
Page 49
BS CS Web Programming — Complete Study Notes Final Exam Preparation
2. SOAP vs REST
Feature SOAP REST
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
// 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
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
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;
}
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.
■ .env files must ALWAYS be in .gitignore. Pushing secrets to GitHub is a critical security incident.
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)
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.
Page 55
BS CS Web Programming — Complete Study Notes Final Exam Preparation
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]
// PREVENTION
// 1. Always escape user input before displaying it
const safe = htmlEncode(userInput);
// htmlEncode converts < to <, > to >, etc.
// PREVENTION
// CSRF Token — server puts a secret random token in forms
Page 56
BS CS Web Programming — Complete Study Notes Final Exam Preparation
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.
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
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
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.
Page 58
BS CS Web Programming — Complete Study Notes Final Exam Preparation
Page 59
BS CS Web Programming — Complete Study Notes Final Exam Preparation
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' }));
};
Page 60
BS CS Web Programming — Complete Study Notes Final Exam Preparation
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);
JavaScript vs WebAssembly
Feature JavaScript WebAssembly
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
Caching strategies
Page 62
BS CS Web Programming — Complete Study Notes Final Exam Preparation
Network First Try network, fall back to cache Dynamic content that should be fresh
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
422 Unprocessable Entity Request body is syntactically valid but semantically wrong
502 Bad Gateway Proxy received invalid response from upstream server
XSS Inject JS into page via user content Escape output, CSP header
Page 64
BS CS Web Programming — Complete Study Notes Final Exam Preparation
Frontend HTML, CSS, JS, React, Redux User interface and interactivity
Web Server Nginx, Apache Handle requests, serve files, reverse proxy
Page 65
BS CS Web Programming — Complete Study Notes Final Exam Preparation
CDN Content Delivery Network — servers at edge locations that cache and serve content
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
HTTP HyperText Transfer Protocol — stateless application protocol for the web
npm Node Package Manager — package manager and registry for [Link]
SSR Server-Side Rendering — generating complete HTML on the server before sending to browser
Page 66