Skip to content
Tutorials Center
My learning

Topics

Lesson 101 of 156 ยท Browser APIs

JavaScript Security Basics

Protect your web pages - prevent XSS with safe DOM APIs, add a Content Security Policy, understand CORS and clickjacking, avoid eval and use secure randomness.

Every web page runs code from many sources at once: your own scripts, libraries you installed, analytics snippets, and data that came from users. If an attacker can sneak their own JavaScript into that mix, it runs with all the power your code has. It can read what the user types, call your APIs as that user, change prices on the page or send data anywhere.

Front-end security is mostly about not letting untrusted data become code, and about using the protections browsers already offer. You don't need to be a security specialist to get the basics right. This lesson covers the most common threats (cross-site scripting, unsafe URLs, clickjacking and eval) and the defenses for each: safe DOM APIs, Content Security Policy, CORS, secure randomness and careful dependency management.

The browser is not a safe place for secrets or rules. Anything in your JavaScript (API keys, hidden admin links, price calculations, validation rules) can be read and changed by the user with DevTools. Front-end checks are for convenience; the server must validate every request and enforce every permission.

Cross-site scripting (XSS)

Cross-site scripting, or XSS, happens when text from an untrusted source ends up being interpreted as HTML or JavaScript on your page. The source could be a comment someone posted, a user name, a URL parameter, a file name, or a response from an API.

The most common way it happens in JavaScript is innerHTML with a template string:

JavaScript
// DANGEROUS: name comes from the user
greeting.innerHTML = `<p>Welcome back, ${name}!</p>`;

If name is Sam, all is well. If it's <img src="x" onerror="stealCookies()">, the browser creates an image element, the image fails to load, and the attacker's code runs. Note that a <script> tag inserted with innerHTML does not run, but event handler attributes like onerror do, so innerHTML is never safe for untrusted text.

innerHTML vs textContent with hostile input

The innerHTML button lets the injected code run; textContent shows the same text as harmless characters. In this sandbox, the "attack" can only tint the preview. On a real site, it could do anything your own scripts can.

Safe DOM APIs

The fix is to keep data as data. Use the APIs that treat values as text or attributes, never as markup:

Safe for untrusted values Dangerous with untrusted values
el.textContent = value el.innerHTML = value
document.createElement() + append() el.outerHTML, insertAdjacentHTML()
el.setAttribute("title", value) document.write()
el.dataset.id = value el.setAttribute("onclick", value)
input.value = value eval(), new Function(), setTimeout("string")

Building elements with createElement() and textContent, as in Creating Elements, is safe by construction. When you really need to render user-provided HTML (say, a rich-text comment), run it through a well-maintained sanitizer library that strips scripts and event handlers. Browsers are also adding a built-in Sanitizer API with el.setHTML(html), which removes dangerous markup automatically; it is new and not yet available everywhere, so check support before relying on it.

Frameworks help, until you opt out. React, Vue, Svelte, Blade and most template engines escape values by default. The danger zones are their explicit "raw HTML" escapes, such as dangerouslySetInnerHTML, v-html and {!! !!}. Treat every one of those as a security review point.

Dangerous URLs

Attributes that take URLs need extra care. A link whose href is javascript:alert(1) runs code when clicked, so setting link.href = userInput is unsafe even though it's "just an attribute". Check the protocol with the URL API before using a URL from users:

JS Allowing only safe link URLs and redirects

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The second function guards against open redirects: a login page that blindly follows ?next=https://evil.example helps phishers make malicious links look like yours. Parsing with new URL() and comparing origins handles tricks like //evil.example and odd capitalization that simple string checks miss.

Content Security Policy (CSP)

Even careful teams make mistakes, so browsers offer a second line of defense: a Content Security Policy. It's an HTTP header (or a <meta> tag) that tells the browser which sources of scripts, styles, images and connections the page may use. If injected code slips through, the browser refuses to run it.

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

This policy says: load everything from our own origin by default; run only our own script files plus inline <script nonce="r4nd0m123"> blocks; allow no plugins; don't let anyone change the base URL; and only allow our own site to frame us. The server generates a fresh random nonce for each response and puts it on its own inline scripts, so an attacker can't guess it.

A strict CSP blocks inline event handler attributes (onclick="..."), inline scripts without the nonce, and eval() (unless you add 'unsafe-eval', which you shouldn't). That's one more reason to attach listeners with addEventListener(). Roll a policy out with the Content-Security-Policy-Report-Only header first: it reports violations without blocking anything, so you can fix your own code before enforcing it.

Chromium-based browsers also support Trusted Types (require-trusted-types-for 'script' in the CSP), which makes innerHTML and similar sinks refuse plain strings entirely. Firefox and Safari have added it too (Baseline newly available since February 2026), but older browser versions lack it.

CORS and the same-origin policy, from JavaScript's side

The same-origin policy is the browser's core security rule: a page can freely read data only from its own origin (protocol + host + port). Your script can send a request to another origin with fetch(), but it can't read the response unless that server explicitly allows it with CORS headers such as Access-Control-Allow-Origin.

From JavaScript's point of view, a few things are worth knowing:

  • A blocked cross-origin request rejects with a vague TypeError: Failed to fetch. The detailed reason appears only in the DevTools console, deliberately, so scripts can't probe other sites.
  • CORS is enforced by the browser to protect users, not your server. Tools like curl ignore it. It is not authentication.
  • Adding credentials: "include" to fetch() sends cookies cross-origin, and the server must opt in with Access-Control-Allow-Credentials: true and a specific (non-*) origin.
  • You can't fix a CORS error in front-end code. The server you call must send the headers, or you route the request through your own server.

The HTML course covers the headers, preflight requests and the crossorigin attribute in detail: Cross-Origin Requests and CORS. Cookies have their own cross-site protection, the SameSite attribute, which also defends against cross-site request forgery; see Cookies.

Clickjacking

In a clickjacking attack, an evil page loads your site in an invisible iframe and positions it so the user clicks a button on your site ("Delete account", "Send money") while thinking they're clicking something harmless on theirs.

The defense is a response header that controls who may frame your pages:

HTTP
Content-Security-Policy: frame-ancestors 'self'
X-Frame-Options: SAMEORIGIN

frame-ancestors is the modern header; X-Frame-Options is the older one, still worth sending for very old browsers. Use 'none' / DENY if your pages should never be framed at all. Old JavaScript "frame-busting" tricks (if (top !== self) top.location = self.location) are unreliable; use the headers.

eval and friends

eval(string) runs a string as JavaScript. So do new Function(string), setTimeout(string) and setInterval(string). If any part of that string comes from outside, an attacker can run whatever they like.

JavaScript
// DANGEROUS: data from a server or user becomes code
const settings = eval("(" + responseText + ")");

// Safe: JSON.parse only ever produces data
const settings = JSON.parse(responseText);

// DANGEROUS: string version of setTimeout
setTimeout("updateBadge(" + count + ")", 1000);

// Safe: pass a function
setTimeout(() => updateBadge(count), 1000);

Beyond security, eval is slow (engines can't optimize code around it), hard to debug, and blocked by a strict CSP. There's almost always a better tool: JSON.parse() for data, an object lookup instead of building variable names, and Proxy or plain functions for dynamic behavior.

A related trap is prototype pollution: merging untrusted JSON into objects with a naive deep-merge can set __proto__ properties that affect every object. Skip __proto__, constructor and prototype keys when merging, or merge into Object.create(null) or a Map.

Secure randomness

Math.random() is fine for games and shuffling a playlist, but it is not cryptographically secure: its output can be predicted. For anything security-related (tokens, IDs that must be unguessable, passwords, one-time codes), use the Web Crypto API:

JS Math.random() vs crypto.getRandomValues()

Press Run (or Ctrl + Enter) to see the console output here.

No output.

crypto.randomUUID() returns a random version 4 UUID such as "3b241101-e2bb-4255-8caf-4136c566a962", but it's only defined on secure (HTTPS or localhost) pages. The rejection loop in secureRandomInt() avoids modulo bias: without it, some numbers would come up slightly more often than others. The same crypto.subtle object also offers hashing, signing and encryption, which are best left to well-tested libraries and server code unless you know the field well.

Third-party code and dependencies

Every library you install and every script tag pointing at another domain runs with your page's full power. A single compromised package or CDN can steal data from all your users. Some habits that reduce the risk:

  • Install fewer, better packages. Prefer well-maintained libraries with many users; question one-line packages you could write yourself.
  • Commit your lockfile (package-lock.json or equivalent) so builds install exactly the versions you tested, and review updates instead of upgrading blindly.
  • Run an audit such as npm audit regularly, and keep automated update tools on.
  • Use Subresource Integrity for scripts from CDNs. The browser refuses the file if its content doesn't match the hash:
HTML
<script
  src="https://cdn.example.com/[email protected]/lib.min.js"
  integrity="sha384-...hash of the exact file..."
  crossorigin="anonymous"></script>
  • Limit third-party scripts like analytics and chat widgets, and list their domains in your CSP so nothing else can load.

A front-end security checklist

  • Put untrusted values in the page with textContent, createElement() and setAttribute(), never innerHTML.
  • Validate URLs from users: allow only http:, https: (and maybe mailto:), and check redirect targets' origins.
  • Send a Content Security Policy, starting in report-only mode.
  • Set frame-ancestors (and X-Frame-Options) against clickjacking.
  • Never use eval(), new Function() or string timers with outside data.
  • Use crypto.getRandomValues() or crypto.randomUUID() for anything that must be unguessable.
  • Keep session cookies HttpOnly, Secure and SameSite, and keep secrets on the server.
  • Keep dependencies few, locked, audited and updated.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which line is safe for showing a comment typed by a user?

    textContent always treats the value as plain text. The other three parse it as HTML, so event handler attributes in it can run.
  2. 2. Why isn't link.href = userInput automatically safe?

    Check that the protocol is http: or https: (with new URL()) before using a URL that came from users.
  3. 3. Which tool should generate a password-reset token in the browser?

    Only the Web Crypto API gives cryptographically secure randomness. Math.random() and timestamps can be predicted, and Base64 hides nothing.
  4. 4. What does the CSP directive frame-ancestors 'self' protect against?

    frame-ancestors controls which pages may embed yours in an iframe, so attackers can't overlay it invisibly.
  5. 5. Your fetch to another site fails with a CORS error. Where must the fix happen?

    Only the server can grant cross-origin read access with CORS headers. no-cors gives an opaque response you can't read.

Summary

  • Never trust the browser: validate and authorize everything on the server, and keep secrets out of front-end code.
  • XSS turns untrusted text into code; prevent it with textContent, createElement() and sanitizers instead of innerHTML, and validate URLs with new URL().
  • A Content Security Policy limits where scripts can come from and blocks injected inline code; frame-ancestors stops clickjacking.
  • The same-origin policy and CORS decide which responses scripts may read; CORS errors are fixed on the server.
  • Avoid eval() and string timers, use crypto.getRandomValues() for secrets, and treat every dependency as code running with your page's power.

That completes the Browser APIs chapter. Next: Dates and Times โ€” create, compare and format dates, and avoid time zone traps.