0 day streak
javascript / beginner
Snippet

Sanitizing External Hyperlinks to Prevent XSS in Anchor Tags

Rendering user-provided URLs in href attributes can allow Cross-Site Scripting (XSS) via javascript: URI schemes. Validating protocol prefixes and adding secure rel attributes protects the application.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
function SafeLink({ targetUrl, label }) {
const isSafe = /^https?:\/\//i.test(targetUrl);
const safeHref = isSafe ? targetUrl : '#';
return (
<a href={safeHref} rel="noopener noreferrer" target="_blank">
{label}
</a>
);
}
react
Breakdown
1
const isSafe = /^https?:\/\//i.test(targetUrl);
Validates that the provided URL explicitly starts with http:// or https://.
2
const safeHref = isSafe ? targetUrl : '#';
Falls back to a safe placeholder hash if the URL contains unsafe protocols.
3
rel="noopener noreferrer"
Prevents reverse tabnabbing and isolates window context for external links.