Handling Data Safely

Updated · 11 min read
mediumES2026javascriptsecurityvalidationcsrfsupply-chain

The previous lesson protected the page from injected code. This one protects the data: what comes in (validate it), what must stay hidden (secrets and tokens), what attackers can trick a browser into sending (CSRF), how merging untrusted objects can corrupt every object in a program (prototype pollution), and the code you didn't write but still ship (dependencies). The theme is the same throughout: trust nothing that crosses a boundary, and remember that anything in front-end code is visible to everyone.

In One Minute

  • Validate every input on the server, against a schema: type, range, length, format. Client validation is for convenience only.
  • Front-end code is public: no API secrets, passwords or private keys in it, ever.
  • Keep session tokens in HttpOnly, Secure, SameSite cookies, not in localStorage.
  • Prevent CSRF with SameSite cookies and anti-CSRF tokens for state-changing requests.
  • CORS is not access control: it only stops other websites' scripts from reading responses.
  • Block prototype pollution (skip __proto__ keys, use Map or null-prototype objects), and audit dependencies.

Validate All Input

Every value that crosses into your program (form fields, URL parameters, JSON bodies, files, headers, messages from other windows) is untrusted. Validate its type, range and format, convert it once, and reject anything unexpected:

validate.js▶ Try it
function parsePayment(input) {
  const errors = [];
  const name = typeof input?.name === "string" ? input.name.trim() : "";
  if (name.length < 1 || name.length > 80) errors.push("name must be 1 to 80 characters");
 
  const amount = Number(input?.amount);
  if (!Number.isFinite(amount) || amount <= 0 || amount > 10_000) errors.push("amount must be between 0 and 10,000");
  if (Number.isFinite(amount) && Math.round(amount * 100) !== amount * 100) errors.push("amount can have at most 2 decimals");
 
  const method = input?.method;
  if (!["card", "check", "ach"].includes(method)) errors.push("method must be card, check or ach");
 
  return errors.length ? { ok: false, errors } : { ok: true, value: { name, amountCents: Math.round(amount * 100), method } };
}
 
console.log(parsePayment({ name: " Navika ", amount: "120.50", method: "card" }));
console.log(parsePayment({ name: "", amount: "-5", method: "cash", isAdmin: true }));
Output
{ ok: true, value: { name: 'Navika', amountCents: 12050, method: 'card' } }
{ ok: false, errors: ['name must be 1 to 80 characters', 'amount must be between 0 and 10,000', 'method must be card, check or ach'] }

Explanation: the validator builds a new object containing only the fields it knows, so extra fields such as isAdmin are dropped instead of flowing into the database (a bug called mass assignment). It uses an allowlist for method rather than trying to list bad values.

PrincipleIn practice
Validate on the serverBrowser checks can be bypassed in seconds
Allowlist, don't denylistAccept known-good values; reject everything else
Validate type, range, length, formatLimits also protect against huge inputs
Copy only known fieldsPrevents mass assignment
Convert once, at the edgeInside the program, data has the right types

Schema libraries (such as Zod or Valibot, or JSON Schema validators) express these rules declaratively and produce good error messages.

Secrets Never Belong in Front-End Code

Everything sent to the browser can be read: JavaScript files, source maps, network requests, environment variables baked in by a build tool. An API key in front-end code is a public API key.

Kind of valueWhere it belongs
Database passwords, private API keys, signing keysServer only (environment variables or a secret manager)
Payment provider secret keysServer only; the browser uses the provider's publishable key or hosted fields
Keys meant to be public (maps, analytics)Front end is fine, with restrictions set in the provider's dashboard (allowed domains, quotas)

When the browser needs something that requires a secret, it calls your server, which adds the secret and calls the other service:

proxy-pattern.js
// Browser: no secret here.
const res = await fetch("/api/exchange-rates?base=USD");
 
// Server (Node.js): the secret stays on the server.
const upstream = await fetch(`https://rates.example.com/latest?base=USD`, {
  headers: { Authorization: `Bearer ${process.env.RATES_API_KEY}` },
});

Where Tokens Belong

After login, the browser holds something that proves who the user is: a session ID or a token.

StorageReadable by injected scripts (XSS)Sent automatically to the serverVerdict
HttpOnly; Secure; SameSite=Lax cookieNoYes, to the same siteRecommended for sessions
localStorage / sessionStorageYesNoAvoid for tokens: one XSS bug leaks them
JavaScript variable (in memory)Yes, while the page is openNoAcceptable for short-lived access tokens, refreshed via an HttpOnly cookie

The cookie attributes are set by the server:

Set-Cookie header
Set-Cookie: session=4f9c...; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=3600

CSRF: Cross-Site Request Forgery

Because browsers attach cookies automatically, a malicious site can make the user's browser send a request to your site, with the user's cookies, without the user knowing: a hidden form that posts "transfer $500". The attacker can't read the response, but the action still happens. This is cross-site request forgery (CSRF).

DefenseHow
SameSite=Lax (or Strict) cookiesThe browser doesn't send the cookie with cross-site POST requests; this is the default in modern browsers for cookies without the attribute
Anti-CSRF tokensThe server puts a random token in the page; state-changing requests must send it back in a header or form field, which other sites can't read
Check Origin / Sec-Fetch-Site headersReject state-changing requests that come from other sites
Never change state with GETGET requests should only read
csrf-token.js
const token = document.querySelector('meta[name="csrf-token"]').content;
await fetch("/api/payments", {
  method: "POST",
  headers: { "Content-Type": "application/json", "X-CSRF-Token": token },
  body: JSON.stringify(payment),
});

CORS Is Not Security for Your Server

CORS (see "HTTP, CORS and Errors") lets a server allow other websites' scripts to read its responses. It doesn't stop anyone from sending requests: curl, scripts and other servers ignore CORS entirely, and even browsers send many cross-origin requests (forms, images) without asking. Protect your API with authentication and authorization on every request, never by relying on CORS. And never reflect any Origin back with Access-Control-Allow-Credentials: true, which lets every website read logged-in users' data.

Prototype Pollution

Prototype pollution happens when code merges or assigns untrusted keys into objects, and a key like __proto__ or constructor.prototype reaches Object.prototype, adding properties to every object in the program:

pollution.js▶ Try it
function setPath(obj, path, value) {
  const keys = path.split(".");
  let target = obj;
  for (const key of keys.slice(0, -1)) target = target[key] ??= {};
  target[keys.at(-1)] = value;
}
 
setPath({}, "__proto__.isAdmin", true);
const user = {};
console.log("isAdmin on a brand new object:", user.isAdmin);
delete Object.prototype.isAdmin;
 
function safeSetPath(obj, path, value) {
  const keys = path.split(".");
  if (keys.some((k) => k === "__proto__" || k === "constructor" || k === "prototype")) throw new Error(`unsafe path: ${path}`);
  let target = obj;
  for (const key of keys.slice(0, -1)) target = Object.hasOwn(target, key) ? target[key] : (target[key] = Object.create(null));
  target[keys.at(-1)] = value;
}
 
try {
  safeSetPath({}, "__proto__.isAdmin", true);
} catch (err) {
  console.log(err.message, "| new object:", {}.isAdmin);
}
Output
isAdmin on a brand new object: true
unsafe path: __proto__.isAdmin | new object: undefined
DefenseHow
Reject dangerous keys__proto__, constructor, prototype in any merge or path-setting code
Use data structures without prototypesMap, or Object.create(null) for dictionaries
Validate against a schemaOnly expected keys get through
Freeze prototypes in critical codeObject.freeze(Object.prototype) at startup (test thoroughly)
Keep merge libraries updatedMany past vulnerabilities were in deep-merge helpers

Dependencies and the Supply Chain

Your app ships every package it installs. To keep that safe (see "NPM Packages and Dependencies" for details):

Terminal
npm ci                      # install exactly the lock file
npm audit --omit=dev        # known vulnerabilities in production dependencies
npm audit signatures        # verify registry signatures and provenance
npm outdated                # what can be updated

Add dependencies deliberately, commit the lock file, review updates, and remove packages you no longer use.

Logging and Error Messages

DoDon't
Log enough to investigate: event, user ID, request ID, timeLog passwords, tokens, full card numbers or personal data
Show users general error messagesShow stack traces, SQL errors or internal hostnames
Mask sensitive values (****1234)Echo secrets back in responses
mask.js▶ Try it
const mask = (value, visible = 4) => `${"*".repeat(Math.max(value.length - visible, 0))}${value.slice(-visible)}`;
const redact = (obj) => Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, /password|token|card/i.test(k) ? mask(String(v)) : v]));
 
console.log(redact({ user: "srihitha@example.com", cardNumber: "4111111111111234", token: "eyJhbGciOiJI", amount: 85 }));
Output
{ user: 'srihitha@example.com', cardNumber: '************1234', token: '********OiJI', amount: 85 }

The token is masked to its last characters only because mask keeps four; for tokens, logging nothing at all is safer.

In Practice

The Fee Tracker's payment endpoint, written as a plain function so it can be tested: it checks the CSRF token, validates and copies only known fields, and never logs sensitive values:

endpoint.js▶ Try it
function handlePaymentRequest({ headers, body, session }) {
  if (headers["x-csrf-token"] !== session.csrfToken) return { status: 403, body: { error: "Invalid request" } };
  if (!session.userId) return { status: 401, body: { error: "Please log in" } };
 
  const amount = Number(body?.amount);
  if (!Number.isFinite(amount) || amount <= 0 || amount > 10_000) {
    return { status: 422, body: { error: "Amount must be between $0.01 and $10,000" } };
  }
  const payment = { studentId: String(body.studentId), amountCents: Math.round(amount * 100), recordedBy: session.userId };
  console.log(`audit: user ${session.userId} recorded ${payment.amountCents} cents`);
  return { status: 201, body: payment };
}
 
const session = { userId: "staff-7", csrfToken: "t-91c" };
console.log(handlePaymentRequest({ headers: { "x-csrf-token": "t-91c" }, body: { studentId: 42, amount: "120.50", isAdmin: true }, session }));
console.log(handlePaymentRequest({ headers: {}, body: { amount: 5 }, session }).status);
console.log(handlePaymentRequest({ headers: { "x-csrf-token": "t-91c" }, body: { amount: "1e9" }, session }).body.error);
Output
audit: user staff-7 recorded 12050 cents
{ status: 201, body: { studentId: '42', amountCents: 12050, recordedBy: 'staff-7' } }
403
Amount must be between $0.01 and $10,000

recordedBy comes from the session, never from the request body, so a user can't claim someone else recorded the payment.

Common Mistakes

Validating only in the browser. Attackers skip the browser. Validate on the server.

Putting secret keys in front-end code or VITE_/NEXT_PUBLIC_ variables. They're public. Use a server.

Storing session tokens in localStorage. Use HttpOnly cookies.

Treating CORS as protection. Authenticate and authorize every request.

Deep-merging untrusted JSON. Filter __proto__ and use schemas.

Interview Corner

Where should you store authentication tokens in the browser?

Prefer an HttpOnly, Secure, SameSite cookie set by the server: scripts (including injected ones) can't read it. localStorage is readable by any script on the origin, so an XSS bug would leak the token. If a token must be in JavaScript, keep it in memory and short-lived, refreshed through an HttpOnly cookie.

What is CSRF and how is it prevented?

Cross-site request forgery makes a victim's browser send an authenticated, state-changing request to a site from another site, using automatically attached cookies. Prevent it with SameSite cookies, anti-CSRF tokens on state-changing requests, checking Origin/Sec-Fetch-Site, and never changing state with GET.

What is prototype pollution?

Injecting properties into Object.prototype (or another shared prototype) through untrusted keys such as __proto__ in merges, path setters or parsers, so every object inherits attacker-chosen values, which can bypass checks or change behavior. Prevent it by rejecting those keys, using Map or null-prototype objects, schema validation, and patched libraries.

Practice

Challenge: Write pickAllowed(input, allowed) that returns a new null-prototype object with only the allowed keys, ignoring dangerous keys even if they're in the allowed list.

Show solution
pick-allowed.js▶ Try it
const DANGEROUS = new Set(["__proto__", "constructor", "prototype"]);
 
function pickAllowed(input, allowed) {
  const out = Object.create(null);
  for (const key of allowed) {
    if (!DANGEROUS.has(key) && Object.hasOwn(input, key)) out[key] = input[key];
  }
  return out;
}
 
const body = JSON.parse('{"name":"Advitha","amount":45,"isAdmin":true,"__proto__":{"x":1}}');
const picked = pickAllowed(body, ["name", "amount", "__proto__"]);
console.log(Object.keys(picked), Object.getPrototypeOf(picked), {}.x);
Output
['name', 'amount'] null undefined

Quick check: Handling data safely

3 questions
1Why isn't client-side validation enough?
2Where should a payment provider's secret key live?
3Does CORS stop attackers from calling your API?

Key Takeaways

RiskDefense
Bad inputServer-side schema validation
Leaked secretsServer-side calls, rotation
Token theftHttpOnly cookies
CSRFSameSite, CSRF tokens, Origin checks
Prototype pollutionReject __proto__, Map, schemas
Vulnerable packagesnpm ci, npm audit, careful updates

Was this tutorial helpful?

Lesson 125 of 139