Allowlist URL schemes in user links
Check that a user-supplied link uses http or https before rendering it as an href, because javascript: and data: URLs run code when clicked.
Rendering <a href="${userUrl}"> lets a user write javascript:alert(1), which runs when someone clicks it. Escaping quotes does not help, because the URL itself is the payload.
function safeHref(input) {
const url = URL.parse(input);
if (!url) return '#';
return ['http:', 'https:', 'mailto:'].includes(url.protocol) ? url.href : '#';
}
console.log(safeHref('https://example.com/a?b=1'));
console.log(safeHref('javascript:alert(1)'));
console.log(safeHref(' JaVaScRiPt:alert(1)'));
console.log(safeHref('data:text/html,<script>alert(1)</script>'));https://example.com/a?b=1
#
#
#The URL parser normalises the scheme, strips leading whitespace and lower-cases it, so odd spellings come out as javascript: and fail the allowlist. Matching the string yourself with startsWith('http') would be fooled by those spellings. Add rel="noopener noreferrer nofollow" for links to other sites. See the OWASP XSS cheat sheet on URLs.
URL.parse needs Node.js 22.1 or a recent browser; new URL in a try block does the same on older runtimes. Relative links are rejected here, so resolve them with a base first if you allow them.