javascript / beginner
Snippet
Preventing Malicious URLs in External Links
Accepting unvalidated URLs from user input can lead to XSS attacks (like javascript: URIs) and reverse tabnabbing. Always validate protocols to ensure only http/https links are rendered, and attach rel='noopener noreferrer' when opening links in new tabs to protect browsing context.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
function SafeExternalLink({ url, label }) {const isSafeProtocol = url.startsWith('https://') || url.startsWith('http://');if (!isSafeProtocol) {return <span className="invalid-link">Invalid Link</span>;}return (<a href={url} target="_blank" rel="noopener noreferrer">{label}</a>);}
react
Breakdown
1
const isSafeProtocol = url.startsWith('https://') || url.startsWith('http://');
Ensures the link protocol begins with http or https, blocking dangerous schemes such as javascript:.
2
if (!isSafeProtocol) {
Checks the security validation result before rendering the clickable anchor tag.
3
<a href={url} target="_blank" rel="noopener noreferrer">
Opens external links safely in a new tab while preventing the new page from accessing window.opener.