For Popcornly I wanted the Next.js cache to have a size limit, so I wrote a custom cache handler. It stored each entry with JSON.stringify and read it back with JSON.parse. Simple enough, until cached pages started failing in production and I went looking for why.
What went wrong
Try this in any JavaScript console:
JSON.stringify(new Map([['a', 1]])); // '{}'
JSON.stringify(new Set([1, 2, 3])); // '{}'
JSON.stringify({ when: new Date(0) }); // '{"when":"1970-01-01T00:00:00.000Z"}', a string now
JSON.stringify({ n: 10n }); // throws: BigInt can't be serialized
JSON.stringify only knows about plain objects, arrays, strings, numbers, booleans and null. Anything else gets converted into one of those. A Map has no enumerable own properties, so it becomes {}. No error, no warning.
A Buffer is a bit sneakier, because it defines toJSON(), so you get { "type": "Buffer", "data": [...] }. That looks fine, but JSON.parse gives you back a plain object with a data array, not a Buffer. Anything that calls .toString('utf8') or reads it as bytes on the way back in gets something else entirely.
App Router cache entries contain both. So every entry my handler saved was quietly broken, and the crash only happened later, when Next tried to read one back. That's what made it hard to find: the bug and the crash were in two different places.
The fix
I stopped serializing data I didn't own. The first fix was to wrap Next's own file-system cache, which knows how to store its own entries, and only add the part I actually wanted: evicting old entries once the cache got too big.
Update, November: I later went one step further and turned Next's data cache off completely. Now Popcornly caches the raw TMDB responses in Redis instead. Those are plain JSON from the start, so JSON.stringify is exactly the right tool for them, and if Redis is down the app just asks TMDB directly.
The bigger lesson for me was to not invent a storage format for data I don't own. If a framework hands you an object to store, it already has a way of storing it, and the shape of that object can change in any minor version. Cache your own data, in a format you control.
How I check for it now
- If a value might be a
Map,Set,Date,Bufferor a class instance,JSON.stringifyis the wrong tool.structuredClonehandles most of these for copies in memory, and libraries likesuperjsonordevaluehandle them over the wire. - Test a round trip, not just a write:
expect(parse(stringify(x))).toEqual(x)would have caught this immediately. - I added a small script that starts the real production build, makes cold and warm requests, and looks for the error messages. I run it before pushing anything that touches server config.
