Skip to content
Back to Guides

Why you get “Maximum call stack size exceeded”, and how to fix it

The Maximum call stack size exceeded error as Chrome, Firefox and Safari word it
LG

Levi Gans

·

Production errors

Plain Text
1RangeError: Maximum call stack size exceeded

“Maximum call stack size exceeded” means a chain of function calls got too deep. Every call puts a frame on the stack, and the engine stops when it runs out of room. Usually that’s a function calling itself with no way out. Sometimes it’s a perfectly normal function handed an array or object that’s bigger than you expected.

The annoying part is the stack trace. It’s ten copies of the same line, and the frame that started the loop is gone.

This guide covers what each browser calls it, the causes we see most, how to find the frame that matters, and fixes that we ran.

The message in each browser

EngineError typeMessage
Chrome, Edge, Node.jsRangeErrorMaximum call stack size exceeded
FirefoxInternalErrortoo much recursion
SafariRangeErrorMaximum call stack size exceeded.

So the full strings are:

Plain Text
1RangeError: Maximum call stack size exceeded2InternalError: too much recursion3RangeError: Maximum call stack size exceeded.

Sources: MDN, SpiderMonkey ErrorNumbers.msg and JavaScriptCore ExceptionHelpers.cpp.

Safari adds a trailing period, which breaks exact string matches in error filters. Firefox’s InternalError isn’t a standard error type, so error instanceof RangeError is false there. If you match on this error, match all three.

We ran the same runaway function in Node.js 24, headless Chrome 158 and Safari’s jsc shell. Node and Chrome threw RangeError: Maximum call stack size exceeded, and jsc threw the same with the period.

What “maximum call stack size exceeded” actually means

The stack has a fixed size, not a fixed number of calls. In Node.js 24, V8’s default is --stack-size=984 kilobytes. How many calls fit depends on how big each frame is.

A function with no arguments and no locals got 10,321 calls deep before it threw in our run. A recursive sum with one argument ran out before 10,000. So “it only recurses ten thousand times” is not a safe assumption.

The common causes

CauseWhat it looks like
No base caseSame function, every frame
Base case never reachedWorks on small input
Mutual recursionTwo functions alternating
Getter or setterget x that reads this.x
toString or valueOfTemplate string inside toString
Deep JSON.stringifyStack ends in stringify
Spreading a huge arrayMath.max(...arr), push(...arr)

Recursion with no way out

The classic version has no base case at all. The sneakier one has a base case that the input never reaches: a condition like n === 0 when n arrives as -1 or 1.5, or a tree where one node points back at its parent.

Mutual recursion is the same thing split across two functions. In our run, an isEven/isOdd pair handled 10,000 fine and overflowed at 100,000. The stack trace alternates between the two names, which is your clue.

Getters and setters that call themselves

This one bites people writing classes:

JavaScript
1class User {2  set name(value) {3    this.name = value.trim();4  }5}6new User().name = "Ada"; // RangeError: Maximum call stack size exceeded

this.name = ... inside the setter calls the setter again. A getter that returns this.name does the same. Store the value somewhere else, such as a private field:

JavaScript
1class User {2  #name = "";3  get name() {4    return this.#name;5  }6  set name(value) {7    this.#name = value.trim();8  }9}

toString and valueOf

toString() { return `${this}`; } converts this to a string, which calls toString(), forever. A valueOf() that does this + 1 loops the same way. Both threw this error when we ran them in Node.js.

JSON.stringify on deep objects

JSON.stringify walks objects recursively. A linked list or tree 100,000 levels deep threw RangeError: Maximum call stack size exceeded in our run.

A circular object is different. It doesn’t overflow. It throws TypeError: Converting circular structure to JSON, and V8 even tells you which property closes the circle. If you see that one, you have a cycle, not a depth problem.

Spreading a huge array

This is the one that surprises people, because there’s no recursion anywhere:

JavaScript
1Math.max(...values);2target.push(...values);3Math.max.apply(null, values);

Spread and apply pass every element as a separate argument, and arguments go on the stack. In Node.js 24, all three worked with 120,000 elements and threw with 130,000. Safari’s jsc handled 100,000 and threw at 1,000,000. MDN warns that the limit “is unspecified and varies across engines.” Code that passed every test with 50 rows falls over the first time a customer has a big account.

Call stack size exceeded in React

React has its own error for render loops, and it isn’t this one:

Plain Text
1Maximum update depth exceeded. This could be an infinite loop.

React throws that when a component keeps calling setState during render or inside useLayoutEffect. The React source caps nested updates at 50. A setState inside a useEffect that has no dependency array, or a dependency that changes every render, gets a console.error with the same “Maximum update depth exceeded” wording instead.

So if a React app shows RangeError: Maximum call stack size exceeded, the loop is usually in plain JavaScript that React happens to call: a recursive helper in a component, a getter on a model class, or a JSON.stringify of deeply nested state. Fix it like any other recursion. If you see “Maximum update depth exceeded”, look at your effects and their dependency arrays.

How to find the frame that started it

By default V8 keeps 10 frames per stack trace. Node.js documents that default for Error.stackTraceLimit. When the stack overflows, those 10 frames are all the repeating function, and the caller that kicked it off is cut off.

Raise the limit before the error happens:

JavaScript
1Error.stackTraceLimit = Infinity;

With that set, our overflow captured 10,327 frames. Scroll to the bottom of the trace and the first frame that isn’t the repeating function is the one that started it. V8’s docs say the value applies only to the current context, so set it in each page or worker. Don’t leave it at Infinity in production. V8 picked 10 because more frames cost time on every error.

The Chrome DevTools debugger is often faster. Check Pause on uncaught exceptions in the Sources panel, reproduce, and walk the call stack down to the first frame that’s yours.

Should you raise --stack-size in Node.js?

node --stack-size=4000 gave our test function 42,489 calls instead of about 10,000. It’s tempting.

But --stack-size tells V8 how much stack it may use, not how much the operating system gives the thread. At --stack-size=65500 our Node.js process crashed with a segmentation fault (exit code 139) instead of throwing a catchable error. It’s also not allowed in NODE_OPTIONS; Node prints --stack-size= is not allowed in NODE_OPTIONS. And it does nothing for your users’ browsers. Treat it as a debugging aid, and fix the code.

How to fix it

Turn the recursion into a loop

Most recursion over a counter is a loop in disguise. A sum to a million is a for loop that never touches the stack.

For trees and graphs, keep your own stack in an array. Arrays live on the heap, which is far larger:

JavaScript
1function countNodes(root) {2  const stack = [root];3  let count = 0;4  while (stack.length > 0) {5    const node = stack.pop();6    count++;7    for (const child of node.children) stack.push(child);8  }9  return count;10}

On a tree 100,000 levels deep, the recursive version threw. This one returned 100001. If your data can contain cycles, add a Set of visited nodes.

Use a trampoline when the recursion is easier to read

Writing the function in tail-call form doesn’t save you. In Node.js 24, a tail-recursive sum to a million still overflowed, even in strict mode. A trampoline gets the effect you wanted by returning a function instead of calling it:

JavaScript
1function trampoline(fn) {2  return (...args) => {3    let result = fn(...args);4    while (typeof result === "function") result = result();5    return result;6  };7}89const sumTo = trampoline(function step(n, total = 0) {10  return n === 0 ? total : () => step(n - 1, total + n);11});1213sumTo(1_000_000); // 500000500000

It only works if the real result is never a function. For most code, the explicit stack above is clearer.

Don’t spread arrays of unknown size

Replace Math.max(...values) with a loop:

JavaScript
1function maxOf(values) {2  let max = -Infinity;3  for (const value of values) if (value > max) max = value;4  return max;5}

If you need push(...), do it in chunks:

JavaScript
1function pushAll(target, source, chunkSize = 10_000) {2  for (let i = 0; i < source.length; i += chunkSize) {3    target.push(...source.slice(i, i + chunkSize));4  }5  return target;6}

Both handled a million elements in our run.

Make JSON.stringify safe for logging

For a cycle, a replacer with a WeakSet stops the walk:

JavaScript
1function stringifySafe(value) {2  const seen = new WeakSet();3  return JSON.stringify(value, (key, val) => {4    if (typeof val === "object" && val !== null) {5      if (seen.has(val)) return "[Circular]";6      seen.add(val);7    }8    return val;9  });10}

It also replaces an object that shows up twice without a cycle, which is fine for logs and wrong for data you’ll read back. For very deep structures, the fix is a shallower shape, or a serializer that walks with an explicit stack.

Catch it in production with Interfere

Interfere is an error tracker for web apps that sorts each problem by how many users it affects, shows which customer accounts and customer tiers it hits, investigates the likely cause, and hands it to your coding agent over MCP.

Error tools were built for teams that shipped a few times a week and read every diff. Coding agents now push hundreds of pull requests to production a day, and nobody reads them all. A new recursive helper or a Math.max(...rows) ships, and production is where you find out. Interfere does the first pass: it groups the errors, works out who each problem hurts, investigates the cause and hands the fix to an agent. It’s how we keep our sanity shipping this way.

The costly stack overflows are quiet. A spread that only fails on very large accounts might hit six people a day, under a harmless error firing 40,000 times. Interfere groups related occurrences into one problem and ranks by affected users, so the quiet one gets its own row.

The Inbox shows which customer tiers each problem reaches, using tiers you set through our API, and Companies names the accounts. Four users on Enterprise can matter more than four hundred on Free, and you set the priority to match. We think that’s a better way to decide what to fix than counting events.

Each problem comes with traces, logs, a session replay from up to seven seconds before the error, and the likely cause tied to a release and code. When the investigation can show the cause in code, it suggests a fix, and your agent picks it up over MCP. Interfere never opens pull requests itself.

It’s built for web apps, with SDKs for Next.js, React with Vite and TanStack Start. There are no mobile SDKs and no profiling. See Cannot read properties of undefined, how to prioritize bugs by user impact, or set up Interfere.

The short version

“Maximum call stack size exceeded” means calls went too deep. Look for a function that calls itself, a getter or setter that touches its own name, or a spread over an array that grew. Set Error.stackTraceLimit = Infinity while you debug to see where the loop started. Then replace the recursion with a loop or an explicit stack. Raising --stack-size only moves the cliff.