JavaScript > Security > Common Vulnerabilities > Cross-Site Scripting (XSS)

XSS Vulnerability: Unsafe URL Parameter Handling

This snippet demonstrates how directly embedding user-supplied URL parameters into links can create XSS vulnerabilities if not properly escaped or validated.

Code Example: Vulnerable Link Generation

This code snippet defines a `createLink` function that dynamically creates an HTML link using user-provided URL and text values extracted from the URL parameters. The function then places this link inside a container element with the ID `linkContainer`. The vulnerability arises from directly injecting the unvalidated `url` and `text` values into the `href` attribute and link text, respectively. A malicious user could inject JavaScript code within the URL (e.g., `javascript:alert('XSS')`) or the text to execute arbitrary scripts.

// WARNING: This code is vulnerable to XSS!
function createLink(url, text) {
  const linkContainer = document.getElementById('linkContainer');
  linkContainer.innerHTML = `<a href="${url}">${text}</a>`;
}

// Simulate getting URL and text from URL parameters.
const urlParams = new URLSearchParams(window.location.search);
const url = urlParams.get('url') || '#';
const text = urlParams.get('text') || 'Click Here';

createLink(url, text);

The Problem: Unescaped URL and Text

The primary issue is that the `url` and `text` variables, derived directly from the URL parameters, are used without any sanitization or encoding. If a user supplies a malicious URL like `javascript:alert('XSS')`, when the link is clicked, the injected JavaScript code will be executed. Similarly, if the `text` parameter contains HTML tags, those tags will be interpreted by the browser, potentially leading to XSS if those tags include `