What is XSS and How to Prevent It

If you've ever heard about hackers putting nasty scripts on sites, then chances are that you're reading about Cross-Site Scripting, or XSS for short. It's one of the most popular and dangerous web attacks, and it can strike anyone from single bloggers to massive companies. Today in this blog, we will dispel myths about what XSS is, how it works, and how you can secure your site or application from it — in easy language.
Prefer watching instead of reading? Here’s a quick video guide
What is XSS?
Cross-Site Scripting (XSS) is an application security vulnerability that enables attackers to inject harmful scripts — most often JavaScript — onto web pages rendered by other users.
Picture yourself browsing a site and, without clicking anything funny, your browser executes a stealthy script that forwards your login cookies to an attacker. That's XSS doing its magic.
These scripts execute on your browser, not the server. This implies the attacker can:
- Steal session cookies (and account takeovers)
- Redirect users to malicious sites
- Show spoofed login forms
- Capture keystrokes or mouse movement
- Alter the DOM (Document Object Model)
Real-World Analogy
Think of a web site like a bulletin board. Anyone can write a note and pin it up for all to see. But suppose that an attacker busts into the bulletin board and posts a note saying, "Click here to log in," and it leads to a spoofed page. Or a note which reads messages without people seeing.
That's XSS — an attacker leading people astray and taking advantage of trust within the site.
XSS: How Does It Work?
Here's a quick explanation of how a simple XSS attack would occur:
- User Input: A site accepts user input (comments, usernames, etc.) without cleaning or sanitizing the input.
- Injection: The attacker injects code instead of text.
- Storage/Reflection: The site stores or reflects the malicious script unfiltered.
- Execution: When another user browses the page, the attacker's script gets executed in the victim's browser.
- Impact: The script may pass information (e.g., cookies or form data) to the attacker.
XSS Types
There are three types of XSS:
- Stored XSS (Persistent)
The malicious script is stored permanently on the server (e.g., in a database).
• The script executes every time a user views the infected page.
• Example: A blog comment field that stores and outputs user input without sanitizing. - Reflected XSS (Non-Persistent)
• The script is not cached; it is reflected from the server response.
• It most likely originates from a URL parameter or form input.
• Example: A search page that renders your query un-sanitized. - DOM-based XSS
• The bug is in client-side JavaScript code.
• The script alters page content based on user input without sanitizing it.
• Example: A JavaScript function reads URL hash and appends it straight into the page.
Why XSS is Dangerous
XSS can seem like just code injection into a website, but it carries some serious consequences:
- Account hijacking (through hijacked session cookies)
- Phishing attacks (impersonation of login forms)
- Malware propagation (through redirects or pop-ups)
- Reading clipboard or browser history
- Total control over a web application's front end
XSS is so dangerous that it's listed on the OWASP Top 10 — a top 10 list of the most critical web application security threats.
Avoiding XSS
And the best news: XSS can be prevented. Here's how to protect yourself:
1: Sanitize User Input
Always consider user input as untrusted. Use input validation to only accept expected formats (e.g., alphanumeric, no tags).
• For instance, if you're expecting a username, disallow characters such as <, >, "\" etc.
2: Escape Output
Escape special HTML characters prior to outputting user data on a webpage:
Character |
Replace With |
---|---|
< |
< |
> |
> |
" |
" |
' |
' |
/ |
/ |
Most frameworks nowadays have built-in escaping. Use it!
3: Use Content Security Policy
A Content Security Policy is a browser feature that limits which scripts are allowed to execute on a page.
<button onclick="doSomething()">Click Me</button>
This stops inline scripts or scripts from unknown sources from executing.
4: Don't Use Inline JavaScript
Do not use inline JavaScript event handlers such as onclick in your HTML. Use event listeners instead to bind JavaScript.
5: Use Safe Frameworks
Newer frameworks such as React, Angular, and Vue escape data automatically during rendering, making it harder for XSS.
6: Sanitize HTML Inputs
If your website allows rich text (e.g., blog articles, comments), use a secure library such as:
- DOMPurify
- Bleach (Python)
- sanitize-html (Node.js)
These libraries remove or sanitize tags and attributes in malicious HTML input.
7: HTTPOnly Cookies
Make session cookies HttpOnly so attackers cannot access them through JavaScript.
Set-Cookie: sessionId=abc123; HttpOnly
This will not prevent XSS, but if an attacker will attempt to sniff cookies, effect will be minimized.
Quick Prevention Checklist
- Sanitize all user inputs.
- Hide escape output from being seen.
- Enforce CSP headers.
- Block unsafe HTML/JavaScript injection.
- Sanitize HTML using libraries if needed.
- Block innerHTML where possible.
- Use framework templating safely.
- Secure cookies and make them HttpOnly.
XSS Example Demo (Try This in a Safe Environment)
Imagine you have a simple page that reflects a query.
<p>Hello, <span id="name"></span>!</p>
<script>
const urlParams = new URLSearchParams(window.location.search);
document.getElementById("name").innerHTML = urlParams.get("name");
</script>
If an attacker browses to a URL and submits a script as the search parameter, and your page places the input directly into the HTML without escaping — the browser will execute the script.
yourpage.html?name=<script>alert('XSS')</script>
Use safer alternatives such as textContent instead of risky ones like innerHTML to prevent this.
document.getElementById("name").textContent = urlParams.get("name");
Final Thoughts
XSS may sound technical, but the concept is simple — don't trust user input and don't blindly inject it into the page. You, as a developer, must be the gatekeeper between what users provide and what your site shows.
Begin with a sweep through your forms, comments, and any user-posted content. Employ new libraries, sanitize gingerly, and employ adequate browser security features such as CSP. With some defensive coding and extra vigilance, you can immunize your site and users from this evil weakness.
Bonus Resources
- OWASP XSS Cheat Sheet
- Google's Web Fundamentals on XSS
- PortSwigger Web Security Academy – XSS Labs