Deloitte Fast 500™ winner in North America: 640% growth Read the news
7 min read

What Is JavaScript Security? Risks, Attacks and Best Practices

JavaScript security is the set of practices and controls that protect JavaScript code, and the users who run it, from abuse. JavaScript runs in almost every browser session and powers server-side applications through Node.js, which makes it one of the largest attack surfaces on the internet. A single malicious or vulnerable script can steal credentials, skim payment cards, or give attackers a foothold in a build pipeline. The challenge is that most JavaScript on a modern site is not written by the site owner. Frameworks, open source packages, analytics tags, chat widgets, and ad scripts all execute with the same privileges as first-party code, often loaded from domains the organization does not control.

Key Takeaways

  • JavaScript security covers client-side code in the browser and server-side code in Node.js
  • Cross-site scripting (XSS), supply chain compromise, and e-skimming are the most damaging JavaScript threats
  • Third-party scripts run with full access to the page, so a compromise at one provider can affect thousands of sites
  • Content Security Policy, Subresource Integrity, and dependency controls form the core defensive layer
  • PCI DSS v4.0.1 requires inventory, authorization, and change detection for scripts on payment pages

Why Is JavaScript a Prime Target?

Attackers focus on JavaScript for three reasons:
  • Reach: a script loaded on a popular site runs in every visitor’s browser
  • Trust: browsers execute any script the page includes, with access to forms, cookies (unless protected), and the DOM
  • Dependency depth: a typical web project pulls in hundreds of transitive npm packages, and each maintainer account is a potential entry point
Client-side attacks are also hard to see. The malicious code runs in the user’s browser, so server logs and network perimeter tools often record nothing unusual.

Common JavaScript Security Threats

Cross-Site Scripting (XSS)

XSS lets an attacker run their own JavaScript in a victim’s browser in the context of a trusted site. It comes in three main forms:
  • Stored XSS: the payload is saved in the application, such as in a comment or profile field, and runs for every viewer
  • Reflected XSS: the payload is part of a crafted link and is reflected back in the response
  • DOM-based XSS: client-side code writes untrusted input into the page with dangerous sinks such as innerHTML, document.write, or eval
Once running, the script can steal session tokens, perform actions as the user, or rewrite the page into a phishing form.

Software Supply Chain Attacks

Attackers compromise or impersonate packages that developers install. Techniques include typosquatting popular package names, taking over abandoned packages, phishing maintainers to publish malicious versions, and abusing install scripts that run automatically. In 2024, the polyfill.io domain changed ownership and began serving malicious code to more than 100,000 websites that still loaded it, which showed how a single third-party script source can become a mass distribution channel. MITRE ATT&CK tracks this as Compromise Software Supply Chain (T1195.002).
How a compromised third-party script source turns into data theft on downstream websites
How a compromised third-party script source turns into data theft on downstream websites

E-Skimming and Magecart Attacks

E-skimming groups, often referred to as Magecart, inject JavaScript into checkout pages to copy card data as customers type it. The skimmer sends the data to an attacker-controlled domain, often disguised as an analytics or CDN endpoint. The checkout still completes normally, so victims and merchants may not notice for months.

Prototype Pollution

JavaScript objects inherit properties from a shared prototype. If an application merges untrusted input into objects without filtering keys such as __proto__ or constructor, an attacker can add properties to every object in the application. Depending on how the code uses those properties, the result ranges from logic bypass to XSS in the browser or remote code execution in Node.js.

Insecure Client-Side Storage

Storing access tokens or personal data in localStorage or sessionStorage exposes them to any script on the page, including injected ones. Hardcoded API keys in bundled JavaScript are also a frequent finding, since anyone can read a site’s front-end source.

Server-Side JavaScript Risks

Node.js applications face classic server vulnerabilities expressed through JavaScript: command injection through child_process, insecure deserialization, path traversal, NoSQL injection, and regular expression denial of service (ReDoS) caused by inefficient patterns that block the single-threaded event loop.

JavaScript Threats at a Glance

Threat Where It Runs Typical Impact
XSS Browser Session theft, account takeover, phishing
Supply chain compromise Build pipeline, browser, server Mass code execution, credential theft
E-skimming Browser (checkout pages) Payment card theft
Prototype pollution Browser or Node.js Logic bypass, XSS, remote code execution
Insecure storage and exposed keys Browser Token theft, API abuse
ReDoS Node.js Service outage

JavaScript Security Best Practices

Core JavaScript security controls across script execution, code, dependencies and production monitoring
Core JavaScript security controls across script execution, code, dependencies and production monitoring

Control What Scripts Can Run

  • Content Security Policy (CSP): restrict script sources with an allowlist, nonces, or hashes, and avoid unsafe-inline and unsafe-eval
  • Subresource Integrity (SRI): add an integrity hash to third-party script tags so the browser refuses modified files
  • Trusted Types: enforce safe handling of DOM sinks to block DOM-based XSS at the browser level
  • Self-hosting: host critical third-party libraries yourself instead of loading them from external CDNs

Write Safer Code

  • Encode output by context and avoid dangerous sinks such as innerHTML and eval
  • Validate and sanitize all input, including JSON keys, to block prototype pollution
  • Set cookies with HttpOnly, Secure, and SameSite attributes
  • Keep secrets out of front-end bundles and enforce authorization on the server

Secure the Dependency Chain

  • Pin versions with lockfiles and review changes before upgrades
  • Scan dependencies continuously with software composition analysis
  • Disable or review package install scripts in CI pipelines
  • Generate a software bill of materials (SBOM) to know what ships in each release
  • Require multi-factor authentication for package registry and repository accounts

Monitor Scripts in Production

  • Maintain an inventory of every script on sensitive pages, along with its source and business justification
  • Detect unauthorized changes to scripts and HTTP headers on payment pages
  • Use CSP reporting to surface blocked or unexpected script loads

JavaScript Security and Compliance

PCI DSS v4.0 introduced two requirements aimed directly at client-side JavaScript on payment pages. Requirement 6.4.3 calls for authorizing each script, confirming its integrity, and keeping an inventory with written justification. Requirement 11.6.1 calls for a mechanism that detects unauthorized changes to payment page scripts and security-relevant HTTP headers. Both became mandatory on March 31, 2025, and remain in PCI DSS v4.0.1, the current version of the standard.

How Can SOCRadar Help?

SOCRadar Attack Surface Management discovers internet-facing web assets, including forgotten subdomains and outdated JavaScript libraries with known vulnerabilities. Vulnerability Intelligence prioritizes library and framework CVEs by real-world exploitation, and Cyber Threat Intelligence tracks skimming infrastructure and supply chain campaigns that target JavaScript ecosystems.

Frequently Asked Questions

What Is JavaScript Security?

JavaScript security is the practice of protecting JavaScript code and its users from attacks such as XSS, supply chain compromise, e-skimming, and prototype pollution, in both the browser and Node.js.

What Is the Most Common JavaScript Vulnerability?

Cross-site scripting (XSS) is the most common JavaScript-related vulnerability in web applications. It allows an attacker to execute their own script in a victim’s browser in the context of a trusted site.

How Does Content Security Policy Improve JavaScript Security?

CSP is an HTTP header that tells the browser which script sources are allowed. A strict policy based on nonces or hashes stops most injected scripts from running, even when an XSS flaw exists.

What Is Subresource Integrity?

Subresource Integrity is a browser feature that checks a cryptographic hash of an external script or stylesheet before running it. If the file on the CDN changes, the browser blocks it.

Are npm Packages Safe to Use?

Most npm packages are safe, but the registry is a frequent target for typosquatting, account takeover, and malicious updates. Lockfiles, dependency scanning, install script controls, and review of new dependencies reduce the risk.

What Is a Magecart Attack?

A Magecart attack injects malicious JavaScript into an online store’s checkout page to capture payment card data as customers enter it, then sends that data to an attacker-controlled server.

Is Storing Tokens in localStorage Secure?

Tokens in localStorage can be read by any script running on the page, so a single XSS flaw can expose them. Session cookies with HttpOnly, Secure, and SameSite flags are generally safer for authentication.

Does PCI DSS Cover JavaScript?

Yes. PCI DSS v4.0.1 requirements 6.4.3 and 11.6.1 require organizations to inventory, authorize, and monitor scripts on payment pages for unauthorized changes.
Share:
What Is JavaScript Security? Risks, Attacks and Best Practices