URL Security: encodeURIComponent

#security
#web
#xss

URLs often carry user input, making them a target for attacks like redirection injection and parameter manipulation. Attackers can exploit query parameters to inject scripts or redirect users to malicious sites. Proper sanitization, such as using encodeURIComponent, helps prevent these risks.


Don't
// Melicious: https://mysite.com/?user=
<script>alert('Hacked!')</script>

const user = new URLSearchParams(window.location.search).get("user");
// user = <script>alert('Hacked!')</script>

// Dangerous: Injects script
document.body.innerHTML = `<h1>Welcome, ${user}</h1>`;
Do
// <script>alert('Hacked!')</script>
const user = new URLSearchParams(window.location.search).get("user");
const encoded = encodeURIComponent(user); // ✅ Encodes user input
// encoded = "%3Cscript%3Ealert('Hacked!')%3C%2Fscript%3E"

document.body.innerHTML = `<h1>Welcome, ${params.get("user")}</h1>`;