javascript / expert
Snippet
Custom Symbol.species Subclassing for Immutable Next.js Request Context Wrappers
By customizing Symbol.species on a Map subclass used for Next.js request context, derived map operations return vanilla Map instances rather than leaking subclass context, while encapsulating internal state in private fields.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
export class HeaderMap extends Map {#timestamp = Date.now();static get [Symbol.species]() {return Map;}get metadata() {return Object.freeze({ created: this.#timestamp, count: this.size });}filterByPrefix(prefix) {const matched = new HeaderMap();for (const [key, value] of this) {if (key.startsWith(prefix)) matched.set(key, value);}return matched;}}
nextjs
Breakdown
1
#timestamp = Date.now();
Declares a hard private class field for contextual timestamp tracking accessible exclusively within class scope.
2
static get [Symbol.species]() { return Map; }
Overrides the default species constructor so internal built-in transformations yield base Map objects to avoid prototype contamination.