#64 · Caching and state

Find the bug · #64 · Caching and state Medium JavaScript

One user’s currency shows up for everyone

After a US customer visits, Indian customers start seeing prices in dollars.

On this page

The report

Bug report

The shop lets users pick a currency. Since a customer from the US visited, everyone else sees prices in USD too, until the server restarts.

The code

Read it first: what should it do? Then click the line where you think the bug is.

JavaScriptClick the line you think is wrong
const DEFAULTS = { currency: 'INR', locale: 'en-IN' };

// The settings for one request: the defaults, with the user's choices on top.
function settingsFor(user) {
  const settings = DEFAULTS;
  if (user.currency) settings.currency = user.currency;
  return settings;
}

Read it, then pick a line.

What it prints

Running it on a small example prints the output on the left. It should print the output on the right.

The example
console.log(settingsFor({ name: 'Sam', currency: 'USD' }).currency);
console.log(settingsFor({ name: 'Asha' }).currency);

It prints

USD
USD

It should print

USD
INR
Show the answer: the bug, the fix, and how you’d find it

The bug (line 5)

Line 5 doesn’t copy the defaults: settings is the shared DEFAULTS object. Line 6 then writes the user’s currency into it, changing the defaults for every request that comes after, on the whole server. Start each request from a copy.

The fix

2 3// The settings for one request: the defaults, with the user's choices on top.4function settingsFor(user) {5  const settings = DEFAULTS;5  const settings = { ...DEFAULTS };6  if (user.currency) settings.currency = user.currency;7  return settings;8}

How you’d find it

  1. Reproduce: one request with USD, then one with no preference. The second gets USD.
  2. One request changed what another sees, so they share an object. Print DEFAULTS after the first request: its currency is now USD.
  3. Line 5 assigns the object instead of copying it, and line 6 writes through it.

The test that catches it

It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.

settingsFor({ currency: 'EUR' });
assert.equal(settingsFor({}).currency, 'INR');
assert.equal(DEFAULTS.currency, 'INR');

Where else this bites

  • The same as “Cancel doesn’t cancel”, but across users instead of within one.
  • Mutating a module-level config in serverless functions, which reuse the same process between calls.
Your progress stays on this device.