Back
Web Fundamentals

Cross-Site Scripting (XSS) Attacks

Web Fundamentals
Build & Deployment: Monorepo, CI/CD, Strategies & Release SafetyState Management: Choosing the Right SolutionRedux: Predictable State Container (RTK + RTK Query)React Query (TanStack Query): Server State CachingData Fetching Patterns: REST, GraphQL, tRPC & Real-timeGraphQL Fundamentals for Frontend: Shape, Caching, and TradeoffsgRPC-Web Fundamentals: Browser Constraints and Proxy ModelCaching Strategies: Client, Server & EdgeData Normalization: Organizing State for PerformanceAPI Design Best Practices: Pagination, Errors, Versioning & Type SafetyAPI Versioning Strategies for Frontend CompatibilityPagination: Offset vs Cursor-BasedRate Limiting & API Resilience: Retries, Backoff, Jitter, IdempotencyHow Frontend Developers Can Handle Millions of API Requests Without Crashing EverythingBrowser Storage: Cookies, SessionStorage, LocalStorage, IndexedDBReal-time Communication: WebSockets, SSE & PollingWebRTC: Real-Time Communication in the BrowserCore Web Vitals: LCP, INP & CLSPerformance Optimization Trade-offsCritical Resource Prioritization: Optimize Loading OrderCode Splitting: Optimize Bundle Size with Dynamic ImportsTree Shaking: Eliminate Dead Code from Your BundleLazy Loading: Load Resources On-DemandResource Hints: Preload, Prefetch & PreconnectText Compression: Gzip and BrotliImage & Video Optimization: Modern Formats & TechniquesAdaptive Loading: Optimize for Device & NetworkList Virtualization: Render Large Lists EfficientlyWeb Workers vs Main Thread: Offloading Heavy WorkMemory Leaks in Frontend Apps: Detection & PreventionManaging Third-Party Scripts: Optimization StrategiesHow CDNs Work: Edge Delivery, Caching & PerformanceHTTP Caching Deep Dive: Cache-Control, ETag & RevalidationService Workers & Offline Strategy: Cache First, Network First & Update LifecyclePWA Fundamentals: Manifest, Installability & Offline UXCritical Rendering PathScript Loading: async vs deferEvent Loop: Understanding JavaScript Execution ModelJavaScript Module Systems: CJS vs ESM vs UMDDynamic Module Loading: import() FunctionImport on Interaction: Load When User InteractsImport on Visibility: Lazy Loading with IntersectionObserverBrowser Rendering Pipeline & Layout ThrashingRendering Strategies: CSR vs SSR vs SSG vs ISRStreaming SSR: Progressive HTML StreamingIslands Architecture: Independent Component HydrationReact Server Components: Zero-JS Server RenderingFramework Reactivity: React, Vue, Svelte & SolidHTTP/1.1 vs HTTP/2 vs HTTP/3 (QUIC) for Frontend PerformanceDNS Resolution: Path, TTL, Caching & Frontend ImpactCross-Site Scripting (XSS) AttacksCross-Site Request Forgery (CSRF) AttacksCORS Explained: Cross-Origin Resource SharingCORS Preflight in Practice: Credentials, Simple Requests & MisconfigurationsContent Security Policy (CSP)Why is HTTPS Secure? Understanding TLS/SSLAuthorization Best PracticesCookie Security & Session Hardening: SameSite, HttpOnly, Secure
mediumSecurity

Cross-Site Scripting (XSS) Attacks

TL;DRXSS = attacker injects malicious script that executes in victim's browser. Prevent with input sanitization, output encoding, CSP, and framework escaping.
High Signal
Google
Meta
Netflix
Agoda
30-Second Answerstart every interview with this

Cross-Site Scripting (XSS) allows attackers to inject malicious scripts into web pages viewed by other users. These scripts run with the site's privileges, enabling cookie theft, session hijacking, or UI defacement. There are three main types: Stored, Reflected, and DOM-based.

The attacker writes a dangerous note (script) and tricks the website into delivering it to other users. When the victim reads the note in their browser, the script executes as if it came from the trusted site.

1Types of XSS Attacks

XSS attacks are classified into three main types based on how the malicious payload is delivered and executed. Understanding each type helps choose the right prevention strategy.

2Stored XSS (Persistent)

The most dangerous type. Attacker submits malicious script that gets permanently stored on the server (e.g., in a comment or profile). Every user who views the page executes the script.

Attacker submits <script>malicious code</script>
Server stores it in database
Victim loads page
Script executes in victim's browser with full site privileges

3Reflected XSS (Non-Persistent)

Malicious script is reflected back in the server's immediate response, usually via a crafted URL. Requires social engineering (phishing link) to trick the victim.

Attacker creates malicious URL (e.g. ?q=<script>alert(1)</script>)
Sends link to victim
Victim clicks link
Server reflects script in HTML response
Script executes

4DOM-based XSS

Occurs entirely on the client side. Attacker manipulates the URL or other client-side data, and vulnerable JavaScript inserts it into the DOM without proper sanitization.

Attacker sends URL with payload in fragment (#<script>alert(1)</script>)
Client-side JS reads location.hash or similar
Uses innerHTML/document.write()
Script executes (no server involvement)

5XSS Prevention Layers (Defense in Depth)

Never rely on a single layer. Use multiple overlapping protections to stop attacks even if one layer fails.

User Input
Layer 1: Input Validation & Sanitization (whitelist + escape)
Layer 2: Output Encoding (textContent instead of innerHTML)
Layer 3: Content Security Policy (CSP) - blocks inline scripts
Safe Output
PropertyStored XSSReflected XSSDOM-based XSS
ImpactAffects all usersTargeted via phishingNo server involvement
ExampleComment form without sanitizationSearch query reflected in pageReading location.hash and using innerHTML
PersistencePermanent (in DB)Non-persistent (in URL)Client-side only

Stored XSS

Impact

Affects all users

Example

Comment form without sanitization

Persistence

Permanent (in DB)

Reflected XSS

Impact

Targeted via phishing

Example

Search query reflected in page

Persistence

Non-persistent (in URL)

DOM-based XSS

Impact

No server involvement

Example

Reading location.hash and using innerHTML

Persistence

Client-side only

Common questions

  • ›“What are the different types of XSS attacks?”
  • ›“How do you prevent XSS in a web application?”
  • ›“Explain the difference between Stored and Reflected XSS.”
  • ›“What is Content Security Policy (CSP) and how does it help?”

What interviewers look for

  • Clear understanding of all three XSS types with examples
  • Defense-in-depth approach (input + output + CSP)
  • Knowledge of framework auto-escaping and common mistakes
  • Practical prevention strategies (textContent, DOMPurify)

Short answer (60 sec)

XSS allows attackers to inject malicious scripts. Stored persists in DB, Reflected is in URL responses, DOM-based happens client-side. Prevent with input sanitization, output encoding (textContent), CSP, and framework escaping.

Detailed answer (senior level)

Stored XSS saves malicious input to the database and serves it to users. Reflected XSS reflects input from the URL in the response. DOM-based XSS manipulates the DOM on the client without server involvement. Prevention requires multiple layers: validate/sanitize input, escape output (never use innerHTML with user data), implement CSP to block inline scripts, and rely on framework auto-escaping (React, Vue, etc.).

  • Using innerHTML with user input
  • Only sanitizing on the client side
  • Missing CSP or using 'unsafe-inline'
  • Forgetting to escape in template literals or string concatenation
  • Trusting framework escaping without understanding edge cases
Key Takeaways
  • ✓Never trust user input — always sanitize on both client and server
  • ✓Use textContent or framework escaping instead of innerHTML
  • ✓Implement CSP as defense-in-depth
  • ✓Stored XSS affects all users; Reflected requires phishing
  • ✓DOM-based XSS happens entirely client-side
  • ✓Defense-in-depth is the only reliable approach
Previous TopicDNS Resolution: Path, TTL, Caching & Frontend ImpactNext Topic Cross-Site Request Forgery (CSRF) Attacks

On this page