JAVASCRIPT

Prevent XSS Attacks with Server-Side Input Sanitization

Learn to defend against Cross-Site Scripting (XSS) vulnerabilities by sanitizing untrusted user input on the server using the 'xss' library in Node.js before displaying it.

const express = require('express');
const bodyParser = require('body-parser');
const xss = require('xss'); // Library for XSS sanitization

const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

let storedComments = [];

// Route to submit a comment
app.post('/comment', (req, res) => {
  const userInput = req.body.comment;

  // GOOD: Sanitize user input before storing or displaying
  const sanitizedInput = xss(userInput, {
    whiteList: {},
    stripIgnoreTag: true, // strip out all HTML not in whiteList
    stripIgnoreTagBody: ['script'] // strip script tags and their content
  });

  storedComments.push(sanitizedInput);
  console.log('Sanitized Comment:', sanitizedInput);
  res.status(200).send('Comment received and sanitized!');
});

// Route to display comments (simulating rendering)
app.get('/comments', (req, res) => {
  // In a real application, you would render these in a template engine.
  // Here, we just send them as JSON to demonstrate stored sanitized output.
  res.json({ comments: storedComments });
});

// Vulnerable route (DO NOT USE IN PRODUCTION)
app.post('/vulnerable-comment', (req, res) => {
  const userInput = req.body.comment;
  // BAD: Storing or displaying unsanitized user input directly
  storedComments.push(userInput);
  console.log('Vulnerable Comment:', userInput);
  res.status(200).send('Vulnerable comment received!');
});

const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
  console.log('Test with payloads like: <script>alert("XSS!")</script>');
});
How it works: This Node.js Express snippet demonstrates crucial server-side input sanitization to prevent Cross-Site Scripting (XSS) attacks. XSS occurs when an attacker injects malicious client-side scripts into web pages viewed by other users. This code uses the 'xss' library to clean user-provided input, removing or neutralizing dangerous HTML tags and attributes (like `<script>` tags or `onmouseover` attributes) before the data is stored or rendered. While client-side validation provides a good user experience, server-side sanitization is essential as a last line of defense against malicious actors who can bypass client-side checks.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs