Introduction to Web Technologies (HTML, CSS, JS)

Chapter 14
Security, Privacy, Performance, and Governance

Diploma in Full Stack Programming
Introduction to Web Technologies (HTML, CSS, JS)   •   Diploma

Security, Privacy, Performance, and Governance

Introduction and context

A web page is not secure merely because it displays correctly in a browser. Modern web development requires attention to confidentiality, integrity, availability, privacy, accessibility, discoverability, speed, and organisational accountability. HTML defines structure, CSS controls presentation, and JavaScript supplies behaviour; each layer can introduce risks or opportunities for improvement.

Security protects systems and users from unauthorised access or manipulation. Privacy concerns the fair and lawful handling of personal information. Performance concerns how quickly and reliably a page responds. Governance provides the policies, responsibilities, evidence, and review processes that keep development aligned with legal, ethical, and organisational requirements.

These concerns are interdependent. A third-party analytics script may improve business reporting but increase privacy and supply-chain risk. A very aggressive performance optimisation may remove meaningful alternative text and damage accessibility. A permissive content policy may make development convenient but allow injected scripts. Professional practice therefore treats quality as a system of balanced decisions rather than a collection of isolated checklists.

Learning objectives

After completing this chapter, a student should be able to:

  • explain common browser-based threats, including XSS, injection, and CSRF;
  • distinguish validation, sanitisation, encoding, and parameterisation;
  • apply safer cookie and Content Security Policy practices;
  • describe privacy, consent, accessibility, SEO, and governance responsibilities;
  • interpret Core Web Vitals and select suitable performance improvements;
  • conduct a basic security, accessibility, privacy, and performance audit;
  • evaluate trade-offs in a realistic web application.

A security model for front-end developers

The browser enforces a security boundary between a user and a web origin. An origin is commonly defined by scheme, host, and port. The same-origin policy restricts one origin from reading protected resources belonging to another, although controlled cross-origin requests can be enabled through Cross-Origin Resource Sharing (CORS). CORS is not an authentication mechanism; it determines which browser scripts may read responses.

Three broad security objectives are useful:

  • Confidentiality: information is disclosed only to authorised parties.
  • Integrity: information and code are not altered without authorisation.
  • Availability: legitimate users can access the service when required.

Authentication establishes identity; authorisation determines permitted actions. A page should never assume that hiding a button provides authorisation. The server must check permissions for every protected operation.

XSS: cross-site scripting

Cross-site scripting occurs when attacker-controlled content is interpreted as executable code in another user’s browser. Common forms include:

  • Stored XSS: malicious content is saved, such as in a comment or profile field, and later served to users.
  • Reflected XSS: attacker input is immediately reflected in a response, often through a search or error page.
  • DOM-based XSS: client-side JavaScript inserts unsafe data into a dangerous DOM context.

The central defence is context-appropriate output encoding. Text intended as text should be inserted with textContent, not innerHTML:

message.textContent = userSuppliedMessage;

If HTML is genuinely required, use a carefully configured, maintained sanitisation library and a restrictive allow-list. Do not attempt to create a complete HTML sanitizer with a few regular expressions. Dangerous contexts include script blocks, event-handler attributes, CSS expressions in legacy environments, URLs, and HTML markup. Each context requires its own encoding rules.

Injection and parameterisation

Injection occurs when data is confused with instructions. Although SQL injection is primarily a server-side concern, front-end developers influence risk by designing APIs and transmitting untrusted input. The server should use parameterised queries or a safe query builder rather than concatenating strings. Shell, template, LDAP, and NoSQL injection require analogous separation of data from commands.

Client-side validation improves usability but cannot be trusted for security because users can bypass or modify browser code. Server-side validation must enforce type, length, range, format, and business rules. Validation should be based on an allow-list wherever practical.

A useful distinction is:

TechniquePurpose
ValidationDetermines whether input meets an expected specification
SanitisationRemoves or transforms unsafe content
EncodingRepresents data safely for a particular output context
ParameterisationKeeps data separate from executable query or command syntax

CSRF awareness

Cross-site request forgery (CSRF) tricks an authenticated browser into sending an unwanted state-changing request. It is especially relevant when authentication relies on cookies, which browsers may attach automatically.

Defences include anti-CSRF tokens bound to the user session, checking the Origin or Referer header where appropriate, and using suitable cookie SameSite settings. State-changing operations should use appropriate methods such as POST, PUT, or DELETE rather than GET. A GET request should be safe and idempotent from a user-impact perspective; it should not delete an account or transfer funds. CORS does not by itself prevent CSRF, because a request may be sent even when the attacker cannot read its response.

Content Security Policy and browser controls

Content Security Policy (CSP) is an HTTP response policy that restricts permitted resource sources and execution behaviour. A basic example is:

Content-Security-Policy:
  default-src 'self';
  script-src 'self' 'nonce-randomValue';
  style-src 'self';
  img-src 'self' https: data:;
  object-src 'none';
  base-uri 'self';
  frame-ancestors 'none';

A nonce must be unpredictable, generated per response, and applied only to intended inline scripts. Avoid unsafe allowances such as 'unsafe-inline' and 'unsafe-eval' unless a documented, temporary exception is unavoidable. CSP is a defence in depth: it reduces exploitability but does not replace safe DOM manipulation, output encoding, or server-side controls. Begin with Content-Security-Policy-Report-Only to identify legitimate dependencies before enforcement.

Other valuable headers include Strict-Transport-Security (HSTS), X-Content-Type-Options: nosniff, an appropriate Referrer-Policy, and clickjacking protection through frame-ancestors. Headers must be tested across supported browsers and deployment environments.

Cookies, sessions, and privacy

Cookies should contain the minimum necessary information. Prefer an opaque session identifier rather than sensitive personal data. Important attributes include:

  • Secure: sends the cookie only over HTTPS;
  • HttpOnly: prevents JavaScript from reading it, reducing some theft opportunities;
  • SameSite=Lax or Strict: limits cross-site sending; SameSite=None requires Secure;
  • appropriate Domain, Path, and expiration settings.

HttpOnly does not prevent all session abuse: an XSS payload may still perform actions through the victim’s browser. Session identifiers should be rotated after authentication and invalidated on logout or suspected compromise.

Privacy engineering begins with data minimisation: collect only what is needed for a stated purpose, retain it only as long as justified, protect it appropriately, and provide mechanisms for access, correction, deletion, or objection where applicable. Privacy notices should explain purposes, categories, recipients, retention, and user rights in understandable language.

Consent must be informed, specific, freely given, and withdrawable where consent is the legal basis. Do not place non-essential tracking cookies before valid consent, and do not use confusing interface patterns such as preselected acceptance or deliberately hidden rejection controls. Legal requirements differ by jurisdiction; developers should work with the organisation’s privacy and legal advisers rather than treating one regulation as universally applicable.

Accessibility and inclusive quality

Accessibility is both an ethical responsibility and, in many jurisdictions, a legal requirement. The Web Content Accessibility Guidelines (WCAG) organise accessibility around four principles: perceivable, operable, understandable, and robust.

Practical HTML foundations include semantic headings, labelled form controls, meaningful link text, keyboard access, visible focus indicators, sufficient colour contrast, captions for video, and useful alternative text. A decorative image should generally have empty alternative text (alt=""); an informative image needs a concise description of its purpose. ARIA should enhance semantic HTML, not replace it unnecessarily.

An accessibility audit should combine automated tools with manual testing. Automated tools can identify missing labels, contrast failures, and structural anomalies, but they cannot reliably judge whether instructions are understandable or whether a keyboard user can complete a workflow. Test with keyboard-only navigation, zoom and reflow, screen readers where available, reduced motion preferences, and varied input devices.

SEO and ethical discoverability

Search engine optimisation is primarily the practice of making content understandable and useful. Use descriptive titles and headings, semantic HTML, canonical URLs where necessary, descriptive links, structured data only when accurate, and a sensible internal linking structure. Provide an XML sitemap and robots.txt appropriately, but remember that robots.txt is not an access-control system and should not be used to protect confidential information.

SEO must not become manipulation. Cloaking, hidden text, misleading structured data, doorway pages, and copied content can harm users and result in ranking penalties. Accessible, fast, well-structured content often supports both users and search engines, but search ranking is not guaranteed by any single technical feature.

Performance and Core Web Vitals

Performance is experienced as responsiveness, stability, and timely content. Current Core Web Vitals emphasise:

  • Largest Contentful Paint (LCP): loading performance, commonly targeted at 2.5 seconds or less;
  • Interaction to Next Paint (INP): interaction responsiveness, commonly targeted at 200 milliseconds or less;
  • Cumulative Layout Shift (CLS): visual stability, commonly targeted at 0.1 or less.

These are field-oriented measures and should be interpreted using real-user data, not only a developer’s fast device. Laboratory tools help diagnose causes, while field data reveals actual user conditions. Thresholds and metric definitions can evolve, so teams should consult current web-platform documentation.

A useful high-level decomposition is:

Tpage = TDNS + Tconnection + Trequest + Tresponse + Tparse + Trender

Here, Tpage is observed page time, while the component terms represent DNS lookup, connection establishment, request and response transfer, parsing, and rendering. The expression is an explanatory model rather than a universal measurement identity: browser parallelism, caching, redirects, service workers, and competing resources can overlap these activities.

Common optimisation actions include compressing and correctly sizing images, using modern formats where appropriate, lazy-loading below-the-fold media, reducing JavaScript, splitting bundles, eliminating render-blocking resources, setting explicit image dimensions, using caching headers, reducing third-party scripts, and serving assets through an efficient content delivery architecture. Do not optimise blindly. Measure, change one significant factor, and measure again.

Performance has trade-offs. Excessive compression may increase CPU use; aggressive caching can serve stale content; code splitting can create too many network requests; and third-party widgets can damage both performance and privacy. A performance budget—such as a maximum JavaScript transfer size or LCP target—turns vague intentions into reviewable governance criteria.

Governance and audit practice

Governance converts professional values into repeatable controls. A small web project should define ownership for security, privacy, accessibility, content, dependencies, and release approval. Useful artefacts include a risk register, data inventory, threat model, accessibility statement, dependency record, incident procedure, and change log.

A practical development lifecycle is:

  1. Plan: identify users, data, threats, legal duties, and quality targets.
  2. Design: select secure defaults, semantic structures, privacy-preserving analytics, and performance budgets.
  3. Build: use code review, linters, dependency pinning, secret management, and safe APIs.
  4. Test: perform unit, integration, accessibility, security, privacy, and performance tests.
  5. Release: verify headers, cookies, monitoring, rollback, and approvals.
  6. Operate: patch dependencies, review logs, respond to incidents, and reassess risks.

Supply-chain governance is increasingly important. Every external package, font, analytics script, and CDN creates dependency and availability risk. Keep an inventory, remove unnecessary dependencies, monitor advisories, use integrity mechanisms where appropriate, and review licence obligations. Never commit API keys or passwords to a repository; rotate exposed secrets immediately.

AI-assisted coding can accelerate development but does not remove accountability. Generated code may contain insecure DOM operations, obsolete APIs, licensing problems, or fabricated assumptions. Treat it as untrusted output: review it, test it, and ensure that no confidential data is submitted to an unauthorised service.

Illustrative case: a student services portal

Background. A college portal allows students to search courses, update contact details, upload documents, and view attendance. It uses a JavaScript front end, cookie-based sessions, analytics, and several third-party widgets.

Problem. An audit finds that search terms are inserted with innerHTML, a profile form relies only on browser validation, cookies lack Secure, analytics loads before consent, images lack dimensions, and keyboard users cannot open the account menu. Mobile users report slow loading.

Analysis. The search feature presents a DOM-XSS risk. The profile endpoint may accept malformed or unauthorised data if server controls are absent. Session cookies are unnecessarily exposed to network interception. Early analytics may violate the institution’s consent policy. Missing image dimensions can cause layout shifts, while inaccessible navigation excludes users and may indicate weak semantic structure.

Approach. The team replaces innerHTML with textContent, sanitises the one approved rich-text field, and adds server-side validation and authorisation. It sets Secure, HttpOnly, and suitable SameSite attributes, adds CSRF tokens to state-changing forms, and deploys a report-only CSP before enforcement. Analytics is blocked until valid consent. Images receive width and height attributes, large assets are compressed, and non-critical scripts are deferred. The menu is rebuilt with semantic buttons, keyboard support, focus management, and an accessible name. Automated scans are followed by keyboard and screen-reader testing.

Outcome. The portal’s attack surface is reduced, consent becomes meaningful, keyboard completion improves, and field performance improves after the largest images and third-party scripts are addressed. The team records residual risks, assigns owners, and schedules a post-release review.

Learning points. Security fixes must include server controls; privacy is a lifecycle concern; accessibility requires human testing; and performance improvements should be evidence-led. Governance makes these practices repeatable rather than dependent on individual memory.

Challenges and limitations

No single control provides complete protection. CSP may be misconfigured, sanitisation may fail in an overlooked context, and cookies remain valuable to attackers even with protective attributes. Automated scanners produce false positives and false negatives. Consent banners can become formal compliance exercises without genuine user understanding. Core Web Vitals summarise important experiences but cannot represent every user need, network condition, or business interaction. Finally, legal rules vary by country and sector. Professional judgement, current documentation, testing, and specialist advice remain necessary.

Best-practice checklist

  • Treat all external input and third-party code as untrusted.
  • Prefer semantic HTML and safe DOM APIs.
  • Validate on the server and encode for the output context.
  • Use parameterised queries and explicit authorisation.
  • Protect state-changing requests against CSRF.
  • Use HTTPS, secure cookie attributes, and restrictive headers.
  • Collect minimal data and obtain meaningful consent.
  • Test keyboard access, screen readers, contrast, and reflow.
  • Measure field performance and control third-party resources.
  • Maintain inventories, owners, review records, and incident procedures.

Chapter Summary

Secure web engineering combines technical controls with privacy, accessibility, performance, and governance. XSS is reduced through safe DOM APIs, context-aware encoding, and carefully controlled sanitisation. Injection is addressed by separating data from commands through validation and parameterisation. CSRF awareness requires secure request design, tokens, origin checks, and appropriate cookie policies. CSP and security headers provide defence in depth. Privacy requires minimisation, transparent purposes, retention control, and valid consent. Accessibility depends on semantic HTML, inclusive interaction design, and both automated and manual audits. SEO should improve truthful discoverability rather than manipulate search systems. Core Web Vitals provide practical indicators of loading, responsiveness, and layout stability, while measurement guides optimisation. Governance assigns responsibility and embeds these practices throughout the software lifecycle.

Key Terms

  • Accessibility: Designing technology so people with diverse abilities can use it.
  • Authentication: Verifying a user’s identity.
  • Authorisation: Determining what an identified user may do.
  • CORS: A browser mechanism controlling readable cross-origin responses.
  • CSP: A policy restricting permitted content sources and execution behaviour.
  • CSRF: An attack that causes an authenticated browser to perform an unwanted action.
  • Encoding: Representing data safely for a particular output context.
  • HSTS: A policy instructing browsers to use HTTPS for a domain.
  • Injection: Treating untrusted data as executable instructions.
  • LCP: A Core Web Vital measuring the rendering of the largest relevant content element.
  • INP: A responsiveness metric reflecting interaction-to-paint delay.
  • CLS: A metric of unexpected visual movement during loading.
  • Parameterisation: Separating query data from query syntax.
  • Privacy: Fair and appropriate control of personal information.
  • Sanitisation: Transforming or removing unsafe input.
  • Same-origin policy: A browser restriction on cross-origin resource access.
  • Validation: Checking whether input meets an expected specification.
  • XSS: Injection of executable script into a user’s browser.

Review Questions

Short Answer Questions

  1. What is the difference between authentication and authorisation?
  2. Why is client-side validation insufficient as a security control?
  3. State two important cookie attributes and their purposes.
  4. What do LCP, INP, and CLS measure?
  5. Why should textContent generally be preferred to innerHTML for untrusted text?

Long Answer Questions

  1. Explain stored, reflected, and DOM-based XSS and describe appropriate defences.
  2. Discuss how CSP, secure cookies, CSRF tokens, and server-side authorisation complement one another.
  3. Describe a privacy-conscious process for introducing analytics into a web application.
  4. Explain how semantic HTML, keyboard testing, and automated tools contribute to accessibility.
  5. Develop a governance lifecycle for a small web project, from planning through operation.

Analytical / Application Questions

  1. A booking site performs a cancellation through a GET request and authenticates users with cookies. Analyse the risks and propose a safer design.
  2. A page has good laboratory performance but poor field INP and CLS results. Identify likely causes and design an investigation plan.
  3. An organisation wants to add five third-party marketing scripts before obtaining consent. Evaluate the proposal using security, privacy, performance, and governance principles.

Multiple Choice Questions with Answers

Question 1

Which practice most directly reduces DOM-based XSS when displaying untrusted plain text?

A. Insert the value with innerHTML

B. Insert the value with textContent

C. Store the value in a cookie

D. Disable browser caching

Correct Answer: B. Insert the value with textContent

Question 2

What is the primary purpose of parameterised database queries?

A. To improve colour contrast

B. To separate data from query instructions

C. To make cookies persistent

D. To allow cross-origin reading

Correct Answer: B. To separate data from query instructions

Question 3

Which statement about CORS and CSRF is correct?

A. CORS automatically prevents all CSRF requests

B. CSRF exists only when local storage is used

C. CORS controls whether scripts may read cross-origin responses

D. CORS replaces server-side authorisation

Correct Answer: C. CORS controls whether scripts may read cross-origin responses

Question 4

Which cookie attribute prevents JavaScript from reading the cookie?

A. Secure

B. HttpOnly

C. SameSite=None

D. Domain

Correct Answer: B. HttpOnly

Question 5

Which is an appropriate CSP principle?

A. Permit all script sources by default

B. Prefer restrictive sources and avoid unsafe-inline where possible

C. Use CSP instead of output encoding

D. Place passwords in CSP directives

Correct Answer: B. Prefer restrictive sources and avoid unsafe-inline where possible

Question 6

Which Core Web Vital focuses on unexpected visual movement?

A. LCP

B. INP

C. CLS

D. DNS

Correct Answer: C. CLS

Question 7

Why should image dimensions commonly be specified in HTML or CSS?

A. To prevent all image downloads

B. To reduce unexpected layout shifts

C. To disable alternative text

D. To bypass consent requirements

Correct Answer: B. To reduce unexpected layout shifts

Question 8

Which statement best describes server-side validation?

A. It can be omitted if a form has HTML required attributes

B. It is enforceable because the server controls the request-processing boundary

C. It is performed only by search engines

D. It is identical to visual design

Correct Answer: B. It is enforceable because the server controls the request-processing boundary

Question 9

Which accessibility practice is most appropriate for a decorative image?

A. Use a long paragraph as its alt text

B. Use empty alternative text, alt=""

C. Place its description only in a colour legend

D. Make it keyboard-focusable

Correct Answer: B. Use empty alternative text, alt=""

Question 10

Why is robots.txt not suitable for protecting confidential information?

A. It encrypts files incorrectly

B. It is an access-control mechanism enforced by servers

C. It is an advisory crawler instruction and does not restrict authorised access

D. It prevents HTTPS

Correct Answer: C. It is an advisory crawler instruction and does not restrict authorised access

Introduction to Web Technologies (HTML, CSS, JS)
Chapter 14 of 15