nodejs/node · error · TypeError

MemoryCacheStore options.maxCount must be a non-negative int

Error message

MemoryCacheStore options.maxCount must be a non-negative integer

What it means

Thrown by the MemoryCacheStore constructor when opts.maxCount is defined but is not a non-negative integer. maxCount caps the number of cached entries; the guard rejects floats, NaN, negative numbers, numeric strings, and Infinity.

Source

Thrown at deps/undici/src/lib/cache/memory-cache-store.js:44

  #hasEmittedMaxSizeEvent = false

  /**
   * @param {import('../../types/cache-interceptor.d.ts').default.MemoryCacheStoreOpts | undefined} [opts]
   */
  constructor (opts) {
    super()
    if (opts) {
      if (typeof opts !== 'object') {
        throw new TypeError('MemoryCacheStore options must be an object')
      }

      if (opts.maxCount !== undefined) {
        if (
          typeof opts.maxCount !== 'number' ||
          !Number.isInteger(opts.maxCount) ||
          opts.maxCount < 0
        ) {
          throw new TypeError('MemoryCacheStore options.maxCount must be a non-negative integer')
        }
        this.#maxCount = opts.maxCount
      }

      if (opts.maxSize !== undefined) {
        if (
          typeof opts.maxSize !== 'number' ||
          !Number.isInteger(opts.maxSize) ||
          opts.maxSize < 0
        ) {
          throw new TypeError('MemoryCacheStore options.maxSize must be a non-negative integer')
        }
        this.#maxSize = opts.maxSize
      }

      if (opts.maxEntrySize !== undefined) {
        if (
          typeof opts.maxEntrySize !== 'number' ||

View on GitHub (pinned to 1b2de5e052)

Solutions

  1. Pass a non-negative integer: { maxCount: 1000 }.
  2. Parse and validate config values: Number.isInteger(Number(v)) ? Number(v) : undefined.
  3. For 'unlimited', omit maxCount entirely rather than passing Infinity.

Example fix

// before
new MemoryCacheStore({ maxCount: process.env.CACHE_COUNT }) // string

// after
const maxCount = Number(process.env.CACHE_COUNT)
new MemoryCacheStore({
  ...(Number.isInteger(maxCount) && maxCount >= 0 ? { maxCount } : {})
})
Defensive patterns

Strategy: validation

Validate before calling

function optInt(v) {
  const n = Number(v)
  if (!Number.isInteger(n) || n < 0) throw new TypeError('must be a non-negative integer')
  return n
}
// new MemoryCacheStore({ maxCount: optInt(config.count) })

Type guard

function isNonNegInt(v) { return Number.isInteger(v) && v >= 0 }

Prevention

When it happens

Trigger: Passing maxCount: 1.5 (float), maxCount: -1, maxCount: '1000' (string), maxCount: NaN, or maxCount: Infinity.

Common situations: Reading the value from an env var as a string and not parsing/coercing; computing maxCount via division that yields a float; using Infinity to mean 'unlimited' (not allowed — omit the field instead).

Related errors


AI-assisted analysis of nodejs/node@1b2de5e052 (2026-08-13). Data as JSON: /api/errors/74ac32cceae4f24f. Report an issue: GitHub.