Skip to content

Instantly share code, notes, and snippets.

@tsale
Created August 2, 2025 19:28
Show Gist options
  • Select an option

  • Save tsale/81bf9c570172adefcef7ffb289221b81 to your computer and use it in GitHub Desktop.

Select an option

Save tsale/81bf9c570172adefcef7ffb289221b81 to your computer and use it in GitHub Desktop.
JavaScript Security Best Practices

JavaScript Security Best Practices

  • Validate, sanitize, and encode: Always validate user input, sanitize it with libraries like DOMPurify, and encode output to prevent XSS.
  • Implement a Content Security Policy (CSP): Use a CSP header to control which scripts, styles, and media are allowed to execute on your page.
  • Forbid inline scripting: Avoid inline event handlers (onclick) and javascript: URIs as they bypass CSP and increase XSS risk.
  • Prefer textContent over innerHTML: Use textContent or createElement to insert data into the DOM safely, avoiding script execution.
  • Use encodeURIComponent: Choose encodeURIComponent over the deprecated escape function for safer URI handling.
  • Avoid document.write: Use createElement or appendChild instead of document.write to prevent DOM-based XSS.
  • Use setAttribute safely: Do not set dynamic attributes like event handlers with user-provided data.
  • Enable Strict Mode: Always start your scripts with 'use strict'; to catch common errors and prevent unsafe actions.
  • Use Subresource Integrity (SRI): Verify the integrity of external scripts from CDNs using a cryptographic hash.
  • Never use eval(): Avoid eval(), new Function(), setTimeout(), and setInterval() with dynamic, user-controlled strings.
  • Prevent prototype pollution: Freeze object prototypes with Object.freeze(), create prototype-less objects with Object.create(null), or use Map instead of Object.
  • Prioritize backend validation: Remember that client-side validation is for UX only; all critical validation must happen on the server.
  • Avoid the with statement: Do not use the with statement as it complicates static analysis and scope.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment