sanitizeURL
Sanitizes a URL string by removing potentially dangerous schemes.
1/**
2 * Sanitizes a URL string by removing potentially dangerous schemes.
3 *
4 * @param url - The URL string to sanitize.
5 * @returns A sanitized URL string or an empty string if unsafe.
6 */
7export function sanitizeURL(url: string): string {
8 try {
9 const parsed = new URL(url, 'http://localhost'); // Fallback base for relative URLs
10 const safeProtocols = ['http:', 'https:', 'ftp:', 'mailto:', 'tel:'];
11
12 return safeProtocols.includes(parsed.protocol) ? url : '';
13 } catch {
14 return '';
15 }
16}
Protection Against Malicious Schemes
Filters out dangerous protocols like
javascript:
,data:
, orfile:
that could be used for XSS or phishing.Graceful Fallback for Invalid URLs
Automatically returns an empty string if the URL is malformed or cannot be parsed, avoiding runtime errors.
Support for Relative URLs
Uses a fallback base (
http://localhost
) to resolve relative URLs, enabling safer default behavior during parsing.Clear Whitelist Approach
Defines an explicit list of allowed schemes, making it easy to audit or extend based on application needs.
Tests | Examples
1test('sanitizeURL - allows safe http URL', () => {
2 expect(sanitizeURL('http://example.com')).toBe('http://example.com');
3});
4
5test('sanitizeURL - allows https URL', () => {
6 expect(sanitizeURL('https://example.com')).toBe('https://example.com');
7});
8
9test('sanitizeURL - strips javascript: URL', () => {
10 expect(sanitizeURL('javascript:alert(1)')).toBe('');
11});
12
13test('sanitizeURL - strips data: URL', () => {
14 expect(sanitizeURL('data:text/html,<script>alert(1)</script>')).toBe('');
15});
16
17test('sanitizeURL - strips vbscript: URL', () => {
18 expect(sanitizeURL('vbscript:msgbox("x")')).toBe('');
19});
20
21test('sanitizeURL - strips invalid URL', () => {
22 expect(sanitizeURL('not a valid url')).toBe('');
23});
24
25test('sanitizeURL - allows mailto URL', () => {
26 expect(sanitizeURL('mailto:user@example.com')).toBe('mailto:user@example.com');
27});
28
29test('sanitizeURL - allows tel URL', () => {
30 expect(sanitizeURL('tel:+123456789')).toBe('tel:+123456789');
31});
32
33test('sanitizeURL - relative URL with safe base', () => {
34 expect(sanitizeURL('/page?x=1')).toBe('/page?x=1');
35});
Common Use Cases
User-Submitted Links
Sanitize links from forms, comments, or user profiles to prevent XSS injections or malicious redirects.
Rendering Safe Href Attributes
Ensure that anchor or iframe URLs in rendered HTML cannot execute arbitrary scripts.
CMS or Markdown Processing
Clean up embedded links in rich content editors before injecting them into the DOM.
Safe Redirects and Navigation
Prevent client-side redirects to potentially dangerous locations by sanitizing the destination URL.
Security Hardening for Embedded Widgets
Validate and sanitize links before using them in ads, widgets, or third-party plugin environments.