Skip to content
Happy Programming Guide
Start learning
JavaScript

JavaScript Security

XSS, CSRF, dependency risk, token storage and prototype pollution — the JavaScript vulnerabilities that matter, in the browser and in Node.

A closed lock on a wooden door

JavaScript security splits into two problems. In the browser, everything you ship is visible and modifiable by the visitor, so the question is what an attacker can make other people’s browsers do. In Node, you have a server with real privileges and the questions are the familiar ones about input, injection and dependencies. This guide covers both.

1. Cross-site scripting#

The most common browser vulnerability, and almost always the same line of code:

JavaScript
// Dangerous - the comment becomes part of the page structure
element.innerHTML = userComment;

A comment containing a script tag or an image with an error handler now runs with your site’s privileges — it can read cookies, call your API as the logged-in user, and rewrite the page.

JavaScript
// Safe - inserts text, never markup
element.textContent = userComment;

// Safe - attributes set through the API are not parsed as HTML
img.src = userUrl;
link.setAttribute("title", userTitle);

When you genuinely need to insert HTML, sanitise it:

JavaScript
import DOMPurify from "dompurify";

element.innerHTML = DOMPurify.sanitize(userHtml);

Do not write your own sanitiser. The list of ways to smuggle script through a naive filter is long, well documented, and constantly growing.

JavaScript
function safeUrl(value) {
  try {
    const url = new URL(value, window.location.origin);
    return ["http:", "https:"].includes(url.protocol) ? url.href : "#";
  } catch {
    return "#";
  }
}

2. Nothing in the browser is secret#

JavaScript
// All of this is visible to anyone who opens developer tools
const API_KEY = "sk-live-1234567890";
const ADMIN_PASSWORD = "hunter2";

if (user.role === "admin") {
  showAdminPanel();          // the check can simply be edited out
}

Minifying does not help. Environment variables in a front-end build do not help — they are substituted into the bundle at build time and shipped.

Two consequences follow. Secrets belong on a server that acts as a proxy. And every authorisation check must be repeated on the server, because the client-side one is a convenience for honest users, not a control.

3. Where to store a session token#

Location Readable by script Verdict
localStorage yes avoid for tokens
sessionStorage yes avoid for tokens
A normal cookie yes avoid
An HttpOnly cookie no preferred

Anything readable by JavaScript is readable by an injected script. An HttpOnly cookie set by the server cannot be read at all, so an XSS flaw cannot steal the session outright.

Output
Set-Cookie: session=abc123; HttpOnly; Secure; SameSite=Lax; Path=/

All four attributes matter: HttpOnly hides it from script, Secure requires HTTPS, SameSite blocks most cross-site sending, and Path scopes it.

4. Cross-site request forgery#

Because cookies are sent automatically, another site can make a visitor’s browser submit a request to yours while they are logged in. Two defences, used together:

Output
SameSite=Lax        blocks the cookie on most cross-site requests
JavaScript
// Plus a token the other site cannot read
const token = document.querySelector('meta[name="csrf-token"]').content;

await fetch("/api/orders", {
  method: "POST",
  headers: { "Content-Type": "application/json", "X-CSRF-Token": token },
  body: JSON.stringify(order),
});

The server generates the token, ties it to the session, and rejects any state-changing request without a matching one.

5. Content Security Policy#

Output
Content-Security-Policy:
  default-src 'self';
  script-src 'self' 'nonce-r4nd0m';
  object-src 'none';
  base-uri 'self';
  frame-ancestors 'none'

A CSP tells the browser which sources are allowed to load. Its real value is as a second line of defence: even if an XSS flaw gets a script tag onto the page, the browser refuses to execute it without the correct nonce.

Avoid unsafe-inline in the script directive — it removes most of the protection. Use a nonce or a hash instead.

6. CORS is not a security control for you#

JavaScript
// On your server
res.setHeader("Access-Control-Allow-Origin", "https://app.example.com");
res.setHeader("Access-Control-Allow-Credentials", "true");

CORS protects browsers from reading responses they should not. It does nothing against a script, a command-line tool, or anything that is not a browser. Your API still needs authentication and authorisation on every endpoint.

7. Dependencies#

Terminal
npm audit
npm audit fix
npm outdated

A typical front-end project depends on hundreds of packages, most of them transitively. Two habits matter: run an audit in your build pipeline so new advisories fail the build, and commit package-lock.json so installs are reproducible.

Check the package name character by character before installing. Typosquatting — a malicious package under a near-identical name — is a recurring npm attack. Copy the name from the official documentation rather than typing it.

8. eval and its relatives#

JavaScript
eval(userInput);                          // never
new Function(userInput)();                // same thing
setTimeout("doThing(" + input + ")", 0);  // string form is eval
element.setAttribute("onclick", input);   // also executes

There is essentially never a good reason for these in application code. To parse data, use JSON.parse. To choose behaviour by name, use a lookup object.

9. Prototype pollution#

JavaScript
// A naive merge, with untrusted input
function merge(target, source) {
  for (const key in source) {
    if (typeof source[key] === "object") {
      target[key] = merge(target[key] || {}, source[key]);
    } else {
      target[key] = source[key];
    }
  }
  return target;
}

merge({}, JSON.parse('{"__proto__": {"isAdmin": true}}'));

console.log({}.isAdmin);      // true - every object now has it

This has been the root of real vulnerabilities in widely used libraries. The fix is to skip the dangerous keys:

JavaScript
const FORBIDDEN = new Set(["__proto__", "constructor", "prototype"]);

for (const key of Object.keys(source)) {
  if (FORBIDDEN.has(key)) continue;
  // ...
}

Or use Object.create(null) for objects built from untrusted data — it has no prototype to pollute.

10. Node-specific#

JavaScript
// Command injection - a shell interprets the whole string
exec(`convert ${userInput} out.png`);

// Safer - arguments passed separately, no shell
execFile("convert", [userInput, "out.png"]);
JavaScript
// Path traversal
const base = path.resolve("./uploads");
const target = path.resolve(base, req.params.name);

if (!target.startsWith(base + path.sep)) {
  return res.status(400).send("Invalid path");
}
JavaScript
// SQL injection - use parameters, never string building
const rows = await db.query("SELECT * FROM users WHERE email = $1", [email]);
JavaScript
// Sensible defaults for headers
import helmet from "helmet";
app.use(helmet());

A checklist#

  • No innerHTML with user data — use textContent or sanitise
  • No secrets in front-end code, ever
  • Session tokens in HttpOnly, Secure, SameSite cookies
  • CSRF tokens on every state-changing request
  • A Content Security Policy without unsafe-inline
  • Every authorisation check repeated on the server
  • A dependency audit in the build pipeline
  • No eval, and no string form of setTimeout
  • HTTPS everywhere

Questions people ask#

Is a JWT in localStorage really that bad?

It is a well-known trade-off. It is convenient and it means any XSS flaw hands over the token. An HttpOnly cookie removes that path entirely, at the cost of needing CSRF protection — which you should have anyway.

Does minifying my code protect it?

No. It makes reading slightly less pleasant. Anything shipped to a browser should be assumed public.

Do I need CSP if I already escape output?

Escaping is the primary defence; CSP is the safety net for the case you missed. Both, ideally.

How do I check my site quickly?

Run it through an online security-header scanner, then run npm audit. Between them they find a surprising amount in a few minutes.

Where to go next#

Browser storage, and what should never go in itRead next

Keep reading

Keep going — pick your next guide

The fastest way to improve is to read one guide, then build the thing it describes. Start with the basics, or jump straight to a project.

Ask a question or share what worked

Your email address will not be published. Required fields are marked *