XSS in template literals β€” is escaping < and > enough?

TP Tomasz P. Member Joined: Jun 30, 2026
Posts: 84
#1

I am learning to build a small page that shows flat listings from a JSON file. I put the data into HTML with template literals:

list.innerHTML = items.map((i) => `<li><a href="${i.url}">${i.title}</a></li>`).join('');

Somebody told me this is XSS. My questions:
1. If I replace < and > in the title, is it safe?
2. What about the link?
3. Is there a simple rule to remember?

YS Yury Slinkin Staff Β· admin Joined: Jun 6, 2026
Posts: 94
#2

Not enough, because there are three different places in that line and each needs its own handling.

1. Text between tags: escape & < > " '. If you build DOM in the browser, simpler still: don't use innerHTML for text at all.
2. Attribute values: the same escaping, and always inside quotes. Without " escaped, a title like " onmouseover="alert(1) breaks out of the attribute.
3. URLs: escaping does not help against javascript:alert(1), it contains no special characters. Allow only http: and https:.

const ESC = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' };
const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ESC[c]);

function safeUrl(u) {
  try {
    const url = new URL(u, location.href);
    return url.protocol === 'https:' || url.protocol === 'http:' ? url.href : '#';
  } catch {
    return '#';
  }
}

list.innerHTML = items
  .map((i) => `<li><a href="${esc(safeUrl(i.url))}">${esc(i.title)}</a></li>`)
  .join('');

Or without HTML strings at all, which removes the whole class of bugs:

for (const i of items) {
  const a = document.createElement('a');
  a.href = safeUrl(i.url);
  a.textContent = i.title; // text, never parsed as HTML
  const li = document.createElement('li');
  li.append(a);
  list.append(li);
}

The rule to remember: escape for the context where the value lands β€” HTML text, attribute, URL, JavaScript, CSS are all different.

ER Evgeny Rudenko Member Joined: Aug 14, 2026
Posts: 86
#3

One more context people miss on the server side: putting data into a <script> tag as JSON. JSON.stringify does not escape <, so a string containing </script> closes your tag early.

const json = JSON.stringify(data).replace(/</g, '\\u003c');
const html = `<script type="application/json" id="state">${json}</script>`;

< is still < for JSON.parse, but the HTML parser no longer sees a tag.

TP Tomasz P. Member Joined: Jun 30, 2026
Posts: 84
#4

Thank you. Two more:
1. If users can write descriptions with bold and links, I cannot escape everything. What then?
2. Is Content-Security-Policy worth it for a small site?

YS Yury Slinkin Staff Β· admin Joined: Jun 6, 2026
Posts: 94
#5

>>4
1. Then you need a sanitizer with an allow-list of tags and attributes, for example DOMPurify in the browser. Never write your own regex-based "remove script tags" filter, there are too many ways around it. Even better: accept Markdown and render it with a library that escapes raw HTML.

2. Yes, it is the second line of defence when the first one fails. A strict starting point for a site without inline scripts:

Content-Security-Policy: default-src 'self'; script-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'

Start with Content-Security-Policy-Report-Only to see what would break, then switch to enforcing. Inline onclick="..." handlers stop working under this policy, which is a good thing: move them to addEventListener.

AK Anna Kor Member Joined: Jul 4, 2026
Posts: 93
#6

For anyone collecting this into notes, the contexts in one place:
βœ… HTML text: escape, or textContent
βœ… attribute: escape + quotes
βœ… URL: allow-list of protocols
βœ… JSON in <script>: replace < with <
βœ… user HTML: sanitizer, never regex
βœ… CSP as a safety net

Quick reply

Only signed-in members can write. Sign in