Module 9: Tooling, Testing, Debugging, and Security
JavaScript Security: XSS, Input, and Secrets
Recognize common browser-side security mistakes and protect untrusted data.
Frontend JavaScript runs in a security-sensitive environment. Treat user input, API responses, URL parameters, and storage values as untrusted until validated. Client-side validation improves usability, but the server must validate and authorize sensitive operations independently.
Cross-site scripting (XSS)#
XSS can occur when untrusted data is inserted into the page as executable markup or script. For plain text, prefer textContent:
const output = document.querySelector("#output");
const userSuppliedText = new URLSearchParams(location.search).get("name") ?? "";
if (output) output.textContent = userSuppliedText;
Avoid putting untrusted strings into innerHTML, inline event attributes, or dynamic script execution. If HTML is a real requirement, use context-appropriate escaping or a maintained sanitizer and keep the trust boundary explicit.
Secrets and authentication#
Never put private API keys or server credentials into frontend source code; users can inspect client bundles and network requests. Use server-side routes for operations that require private credentials. Do not store session secrets in localStorage as a shortcut.
Dependencies and URLs#
Keep dependencies maintained and review security alerts. Validate URL schemes and destinations when generating links from untrusted input. Use HTTPS for sensitive traffic and server-side authorization for protected data.
Practice#
Inspect a small DOM rendering example and identify whether it uses textContent or innerHTML. Rewrite unsafe plain-text rendering and explain why frontend checks do not replace server-side authorization.