0 day streak
javascript / intermediate
Snippet

Sanitizing Dynamic Href Values against Javascript Scheme Injection

Passing user-controlled input directly into the href attribute of an anchor tag can lead to Cross-Site Scripting (XSS) via URI schemes like 'javascript:'. Validating and sanitizing the URL string prevents execution of injected scripts before the element is rendered.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import React from 'react';
const RESTRICTED_SCHEMES = ['javascript:', 'data:', 'vbscript:'];
function sanitizeDestination(rawUrl) {
if (!rawUrl || typeof rawUrl !== 'string') return '#';
const normalized = rawUrl.trim().toLowerCase();
const isRestricted = RESTRICTED_SCHEMES.some((scheme) => normalized.startsWith(scheme));
return isRestricted ? '#' : rawUrl.trim();
}
export function SecureExternalLink({ targetUrl, linkText }) {
const safeUrl = sanitizeDestination(targetUrl);
const isNavigable = safeUrl !== '#';
return (
<a
href={safeUrl}
target={isNavigable ? '_blank' : undefined}
rel={isNavigable ? 'noopener noreferrer' : undefined}
>
{linkText}
</a>
);
}
react
Breakdown
1
const isRestricted = RESTRICTED_SCHEMES.some((scheme) => normalized.startsWith(scheme));
Checks if the normalized URL begins with dangerous execution schemes such as javascript: or data:.
2
return isRestricted ? '#' : rawUrl.trim();
Falls back to a benign hash if an unsafe scheme is identified.
3
rel={isNavigable ? 'noopener noreferrer' : undefined}
Secures external link navigation against reverse tabnabbing and window.opener hijacking.