Web security is essential for protecting users and data. Two common vulnerabilities are Cross-Site Scripting (XSS) and Cross-Site Request Forgery (CSRF). Understanding their nature and mitigation techniques is crucial for safe JavaScript development.

💡 What is XSS?
XSS attacks occur when an attacker injects malicious scripts into trusted websites, which then execute in other users' browsers, potentially stealing data or hijacking sessions.
💡 What is CSRF?
CSRF tricks a logged-in user’s browser into sending unauthorized requests to a web application, exploiting the user’s authenticated state without their consent.
| Aspect | XSS | CSRF |
|---|---|---|
| Target | End users' browsers | Authenticated users performing actions |
| Attack Vector | Malicious scripts injected into webpages | Unauthorized requests forged from user’s browser |
| Goal | Steal data, hijack session, deface site | Perform unwanted actions on behalf of user |
| Common Defense | Input sanitization, Content Security Policy | CSRF tokens, SameSite cookies |
How XSS Happens
When user input is displayed on a webpage without proper escaping or sanitization, an attacker can insert HTML or JavaScript code that runs in other users’ browsers.
📌 Deep Dive: Unsafe HTML Injection Example
const userInput = '<script>alert("XSS")</script>';
document.getElementById('output').innerHTML = userInput;
Mitigation: Always sanitize or escape user input before inserting it into the DOM. Use safe methods like textContent instead of innerHTML when possible.
How CSRF Works
If a user is logged into a site, their browser sends authentication cookies automatically. An attacker can trick the browser into sending a forged request, for example via a hidden form or image tag on another site.
📌 Deep Dive: CSRF Attack Concept
<img src="https://bank.com/transfer?amount=1000&to=attacker" style="display:none" />
Mitigation: Use anti-CSRF tokens that must be submitted with state-changing requests, and enable SameSite cookie attribute to restrict cross-origin requests.
⚠️ Key Security Practices
- Never trust user input — always sanitize and validate.
- Use Content Security Policies (CSP) to limit script execution.
- Implement CSRF tokens for all sensitive POST/PUT/DELETE requests.
- Set cookies with
HttpOnlyandSameSite=StrictorLax. - Keep libraries and frameworks up to date to patch known vulnerabilities.
💡 Remember
XSS exploits flaws in output handling; CSRF exploits authenticated state and trust. Defenses differ but both require secure coding and server-side protections.
Quick Knowledge Check
Test what you just learned
Question 1 of 2
Which defense mechanism is most effective against Cross-Site Request Forgery (CSRF)?
Question 2 of 2
What is a safe way to insert user input into the page to prevent XSS?
Loading results...