Handling Data Safely
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,SameSitecookies, not inlocalStorage. - Prevent CSRF with
SameSitecookies 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, useMapor 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:
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 }));{ 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.
| Principle | In practice |
|---|---|
| Validate on the server | Browser checks can be bypassed in seconds |
| Allowlist, don't denylist | Accept known-good values; reject everything else |
| Validate type, range, length, format | Limits also protect against huge inputs |
| Copy only known fields | Prevents mass assignment |
| Convert once, at the edge | Inside 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 value | Where it belongs |
|---|---|
| Database passwords, private API keys, signing keys | Server only (environment variables or a secret manager) |
| Payment provider secret keys | Server 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:
// 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.
| Storage | Readable by injected scripts (XSS) | Sent automatically to the server | Verdict |
|---|---|---|---|
HttpOnly; Secure; SameSite=Lax cookie | No | Yes, to the same site | Recommended for sessions |
localStorage / sessionStorage | Yes | No | Avoid for tokens: one XSS bug leaks them |
| JavaScript variable (in memory) | Yes, while the page is open | No | Acceptable for short-lived access tokens, refreshed via an HttpOnly cookie |
The cookie attributes are set by the server:
Set-Cookie: session=4f9c...; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=3600CSRF: 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).
| Defense | How |
|---|---|
SameSite=Lax (or Strict) cookies | The 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 tokens | The 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 headers | Reject state-changing requests that come from other sites |
Never change state with GET | GET requests should only read |
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:
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);
}isAdmin on a brand new object: true
unsafe path: __proto__.isAdmin | new object: undefined| Defense | How |
|---|---|
| Reject dangerous keys | __proto__, constructor, prototype in any merge or path-setting code |
| Use data structures without prototypes | Map, or Object.create(null) for dictionaries |
| Validate against a schema | Only expected keys get through |
| Freeze prototypes in critical code | Object.freeze(Object.prototype) at startup (test thoroughly) |
| Keep merge libraries updated | Many 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):
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 updatedAdd dependencies deliberately, commit the lock file, review updates, and remove packages you no longer use.
Logging and Error Messages
| Do | Don't |
|---|---|
| Log enough to investigate: event, user ID, request ID, time | Log passwords, tokens, full card numbers or personal data |
| Show users general error messages | Show stack traces, SQL errors or internal hostnames |
Mask sensitive values (****1234) | Echo secrets back in responses |
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 }));{ 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:
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);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,000recordedBy 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
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);['name', 'amount'] null undefinedKey Takeaways
| Risk | Defense |
|---|---|
| Bad input | Server-side schema validation |
| Leaked secrets | Server-side calls, rotation |
| Token theft | HttpOnly cookies |
| CSRF | SameSite, CSRF tokens, Origin checks |
| Prototype pollution | Reject __proto__, Map, schemas |
| Vulnerable packages | npm ci, npm audit, careful updates |
Was this tutorial helpful?