Client-Side Security Essentials
Published by Brayan K
Client-side security is the practice of protecting browser-based JavaScript apps from attacks like cross-site scripting (XSS) and cross-site request forgery (CSRF) by sanitizing input, handling tokens safely, and layering defenses.
Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Follow untrusted data to the operation that interprets it
A URL parameter, saved comment, message or API field can be untrusted even when it reaches your code as a string. The important question is what consumes that value: an ordinary text node, an HTML parser, a URL navigation or executable code. One generic “sanitize” function cannot make every context safe.
const comment = '<strong data-demo="yes">Hello</strong>';
const output = document.createElement("p");
// An ordinary paragraph receives text; no markup parser reads the comment.
output.textContent = comment;
document.getElementById("app").append(output);
console.log(output.textContent === comment);
console.log(output.querySelectorAll("strong").length);
// ✅ Expected output:
// true
// 0Use textContent or createTextNode for ordinary displayed text. This is not HTML encoding: do not pre-encode and then assign textContent, or users see the entity spelling. A script or style element is a different context, so “textContent is always safe” is too broad. Keep element names and event wiring under application control.
const text = "<em>hello</em>";
const plain = document.createElement("div"), parsed = document.createElement("div");
plain.textContent = text;
parsed.innerHTML = text;
console.log(plain.childElementCount, parsed.childElementCount);
console.log(plain.textContent, parsed.textContent);
// ✅ Expected output:
// 0 1
// <em>hello</em> helloThe second assignment parses HTML. This example deliberately contains only harmless emphasis markup; replacing it with untrusted input is not an acceptable rendering strategy. When a product needs rich HTML, use a maintained sanitizer with a defined configuration and follow its integration guidance. Regex replacement is not an HTML sanitizer.
Encoding, URL policy and sanitization solve different problems
const element = document.createElement("p");
element.textContent = "<b>hello</b>";
console.log(element.textContent);
console.log(element.querySelectorAll("b").length);
// ✅ Expected output:
// <b>hello</b>
// 0A URL assigned to href still has navigation semantics. HTML escaping does not decide which protocols or destinations your product permits. Parse it with URL, then apply a small explicit policy. Compare the normalized origin; a prefix string check can accept a lookalike host or credentials before another host.
const allowed = "https://docs.example.test";
for (const text of ["https://docs.example.test.evil.test/x", "https://[email protected]/x"]) {
const url = new URL(text);
console.log(text.startsWith(allowed), url.origin === allowed);
}
// ✅ Expected output:
// true false
// true falsefunction approvedLink(text) {
if (typeof text !== "string") throw new TypeError("URL must be text");
const url = new URL(text);
const origins = new Set(["https://docs.example.test", "https://learn.example.test"]);
if (url.protocol !== "https:" || !origins.has(url.origin) || url.username || url.password)
throw new TypeError("URL is outside the approved origins");
return url.href;
}
for (const text of [
"https://docs.example.test/guide",
"HTTPS://DOCS.EXAMPLE.TEST:443/guide",
"javascript:void(0)",
"https://docs.example.test.evil.test/guide",
"https://user:[email protected]/guide"
]) {
try { console.log(new URL(approvedLink(text)).origin); }
catch (error) { console.log(error.name); }
}
// ✅ Expected output:
// https://docs.example.test
// https://docs.example.test
// TypeError
// TypeError
// TypeErrorThese reserved example domains are parsed locally; no request is made. An allowlist does not guarantee the destination’s content, eliminate server-side redirects or authorize a user action. This policy intentionally rejects relative links and every nonlisted origin. A different product needs its own reviewed contract.
function approvedLink(text) {
if (typeof text !== "string") throw new TypeError("URL must be text");
const url = new URL(text);
const origins = new Set(["https://docs.example.test", "https://learn.example.test"]);
if (url.protocol !== "https:" || !origins.has(url.origin) || url.username || url.password)
throw new TypeError("URL is outside the approved origins");
return url.href;
}
approvedLink("javascript:void(0)");
// ✅ Expected error:
// TypeError: URL is outside the approved originsBrowser checks improve feedback; the server owns authorization
const state = { role: "reader" };
const showsAdminButton = () => state.role === "admin";
console.log(showsAdminButton());
state.role = "admin";
console.log(showsAdminButton());
// ✅ Expected output:
// false
// trueHiding a button or validating a form does not protect the server operation. The server must authenticate the caller and authorize each protected action and resource. Never trust a client-supplied role or product price as the authority. Deep Dive into JSON, Parsing & Serialization owns schema validation; valid shape is still not permission.
Secrets bundled into frontend JavaScript are available to users who receive the bundle. Environment-variable syntax does not make a compiled client value private. Keep privileged service credentials on a trusted server, and design any intentionally public client key around server-side authorization and appropriate limits.
CSRF protection requires a server-enforced request contract
Cross-site request forgery targets actions authenticated by credentials the browser attaches automatically, often cookies. A request can change server state even when the attacker cannot read the response. CORS controls browser response access and some request flows; it is not a substitute for authorization or a complete CSRF defense.
// This is a format fixture, not a generated or valid security token.
const token = "fixture-token-not-for-use";
const request = new Request("https://app.example.test/preferences", {
method: "POST", credentials: "same-origin",
headers: { "Content-Type": "application/json", "X-CSRF-Token": token },
body: JSON.stringify({ theme: "dark" })
});
console.log(request.method, request.credentials);
console.log(request.headers.get("X-CSRF-Token") === token);
console.log((await request.json()).theme);
// ✅ Expected output:
// POST same-origin
// true
// darkCreating this Request proves only its local shape. Use your server framework’s supported CSRF protection and validate the token or other chosen defense on the server. An arbitrary header or a token generated only in the browser is not enough. Avoid state-changing GET endpoints. SameSite cookies and origin checks can add defense in depth, but same-site and same-origin are different boundaries.
HttpOnly prevents JavaScript from reading a cookie; it does not stop the browser attaching that cookie to applicable requests or stop injected same-origin script from issuing actions. Secure restricts cookie delivery to secure transport; SameSite controls cross-site sending. Configure them according to the application and verify actual server headers and behavior. Web Storage APIs (localStorage, sessionStorage, IndexedDB) owns storage scope; localStorage is readable by scripts running in that origin.
Messages need identity checks and a data contract
const expectedSource = {}; // A stand-in identity, not a delivered MessageEvent.
function accept(event) {
return event.origin === "https://widget.example.test" &&
event.source === expectedSource &&
event.data !== null && typeof event.data === "object" &&
event.data.type === "resize" &&
Number.isInteger(event.data.height) && event.data.height >= 100 && event.data.height <= 800;
}
const valid = { origin: "https://widget.example.test", source: expectedSource, data: { type: "resize", height: 320 } };
console.log(accept(valid));
console.log(accept({ ...valid, origin: "https://widget.example.test.evil.test" }));
console.log(accept({ ...valid, source: null }));
console.log(accept({ ...valid, data: { type: "resize", height: "320" } }));
// ✅ Expected output:
// true
// false
// false
// falseThese plain event-shaped fixtures test the acceptance predicate, not cross-window delivery. In a real listener, use the actual MessageEvent and expected window reference; do not accept an origin string supplied inside event.data. Specify an exact targetOrigin when sending to a known origin. Opaque origins serialize as null, so null alone cannot identify a trusted sender.
CSP can limit script sources and some dangerous execution paths, while Trusted Types can help enforce policies at supported DOM sinks. They are additional controls, not a reason to keep unsafe rendering. A useful policy needs real deployment headers, reporting and compatibility checks. No CSP header, cookie behavior or live server is verified by these offline examples.
Select data instead of merging arbitrary object keys
const input = JSON.parse('{"title":"Guide","admin":true,"__proto__":{"marker":"unexpected"}}');
const view = { title: typeof input.title === "string" ? input.title : "" };
console.log(Object.keys(view).join(","));
console.log(Object.getPrototypeOf(view) === Object.prototype);
console.log(Object.hasOwn(view, "admin"));
// ✅ Expected output:
// title
// true
// falseSchema validation, output handling and authorization are separate checks along a data flow. Selecting known fields reduces accidental propagation; it does not make a value safe for every later sink. Keep the chosen text or URL boundary where the value is used.
Guided exercise: build a fixed element with a text label
Complete the literal hints. Use an ordinary span with a fixed tag name, then assign the original label as text.
const label = "<b>Read this</b>";
const element = document.___("span"); // 👉 replace ___ with createElement
element.___ = label; // 👉 replace ___ with textContent
document.getElementById("app").append(element);
console.log(element.textContent === label, element.childElementCount);
// ✅ Expected output:
// true 0Independent brief: render an allowlisted resource list
Implement renderResourceList(root, items). Accept an Element and a dense array of at most 20 entries. Each entry needs a title with 1 through 80 trimmed UTF-16 code units and an absolute URL accepted by approvedLink. Validate the whole input before replacing current content. Empty lists are allowed.
Create fixed ul, li and a elements. Put titles in textContent, use the normalized approved URL, and set target to _blank with rel="noopener noreferrer". Replace the root’s contents only after every item is valid and return the number of entries. Treat this as exclusive ownership of that container. Do not add an HTML sanitizer, infer authorization or promise that destinations cannot redirect.
function approvedLink(text) {
if (typeof text !== "string") throw new TypeError("URL must be text");
const url = new URL(text);
const origins = new Set(["https://docs.example.test", "https://learn.example.test"]);
if (url.protocol !== "https:" || !origins.has(url.origin) || url.username || url.password)
throw new TypeError("URL is outside the approved origins");
return url.href;
}
function renderResourceList(root, items) {
if (!(root instanceof Element)) throw new TypeError("root must be an element");
if (!Array.isArray(items) || items.length > 20) throw new TypeError("items must contain at most 20 entries");
const selected = [];
for (let index = 0; index < items.length; index++) {
const item = items[index];
if (!Object.hasOwn(items, index) || item === null || typeof item !== "object" ||
typeof item.title !== "string" || item.title.trim().length < 1 || item.title.trim().length > 80)
throw new TypeError("each title must contain 1..80 trimmed code units");
selected.push({ title: item.title.trim(), href: approvedLink(item.url) });
}
// Validate the whole input before replacing any current content.
const list = document.createElement("ul");
for (const item of selected) {
const row = document.createElement("li"), anchor = document.createElement("a");
anchor.textContent = item.title;
anchor.href = item.href;
anchor.target = "_blank";
anchor.rel = "noopener noreferrer";
row.append(anchor); list.append(row);
}
root.replaceChildren(list);
return selected.length;
}
const root = document.getElementById("app");
console.log(renderResourceList(root, [
{ title: "<img src=x>", url: "https://docs.example.test/start" },
{ title: "Learn", url: "https://learn.example.test/path" }
]));
console.log(root.querySelectorAll("img").length, root.querySelector("a").textContent);
console.log(root.querySelector("a").rel);
const original = root.firstChild;
try {
renderResourceList(root, [
{ title: "Good", url: "https://docs.example.test/ok" },
{ title: "Bad", url: "javascript:void(0)" }
]);
} catch (error) { console.log(error.name, root.firstChild === original); }
console.log(renderResourceList(root, []), root.querySelectorAll("li").length);
// ✅ Expected output:
// 2
// 0 <img src=x>
// noopener noreferrer
// TypeError true
// 0 0Primary security references
Read the OWASP XSS prevention guidance for context-specific sinks and maintained HTML sanitization. Its CSRF prevention guidance explains server-enforced defenses and SameSite limitations. The postMessage reference documents origin/source validation.
Practice quiz
What does this complete program print? const e=document.createElement("p");e.textContent="<b>Hello</b>";console.log(e.childElementCount,e.textContent);
- 0 <b>Hello</b>
- 1 Hello
- 0 Hello
- 1 <b>Hello</b>
Answer: 0 <b>Hello</b>. An ordinary text sink does not parse the string as HTML.
What does this complete program print? const url=new URL("https://[email protected]/x");console.log(url.hostname);
- docs.example.test
- evil.test
- [email protected]
- x
Answer: evil.test. The text before @ is credentials, not the destination hostname.
What does this complete program print? const e=document.createElement("p");e.textContent="<b>";console.log(e.textContent);
- <b>
- b
- <b>
Answer: <b>. Text sinks display the original entity spelling without decoding it.
What does this complete program print? const x={role:"reader"};x.role="admin";console.log(x.role);
- reader
- undefined
- TypeError
- admin
Answer: admin. Client state is mutable and cannot authorize server actions.
What does this complete program print? const x=JSON.parse('{"title":"A","admin":true}');const y={title:x.title};console.log(Object.hasOwn(y,"admin"));
- false
- true
- undefined
- TypeError
Answer: false. Selected fields exclude the untrusted extra property.
What does the offline Request example establish?
- The server has accepted a valid CSRF token
- The local request has the specified method, headers and body
- The cookie is HttpOnly
- The user is authorized
Answer: The local request has the specified method, headers and body. Server enforcement, cookie headers and authorization require separate checks.
Why is checking only a message’s origin insufficient for a narrow widget contract?
- Origins never carry useful information
- JSON data is automatically trusted
- The expected source and message shape still need validation
- Every message should be accepted with targetOrigin *
Answer: The expected source and message shape still need validation. Validate the actual event origin, the expected source where applicable, and the permitted data shape.
A product needs users to submit rich HTML. Which approach fits the lesson?
- Delete script tags with a regex
- Assign it directly to innerHTML after JSON.parse
- Use textContent on a script element
- Use a maintained sanitizer with a reviewed policy and keep it updated
Answer: Use a maintained sanitizer with a reviewed policy and keep it updated. HTML sanitization is a context-specific integration; it is different from displaying literal text.
Continue this course
- Previous: Deep Dive into JSON, Parsing & Serialization
- Next: Working with WebSockets for Real-Time Features — Build live chat, notifications, and dashboards with WebSocket connections
- Quick reference: JavaScript cheat sheet