Skip to content

Conversation

@Stanzilla
Copy link

Summary

This PR fixes a memory leak that occurs when using passthrough mode in Node.js 20+.

The Problem

When MockHttpSocket.passthrough() is called, event listeners are attached to the original socket (lookup, connect, secureConnect, secure, session, ready, drain, data, error, resume, timeout, prefinish, finish, close, end) but they are never removed when the socket closes.

This causes memory leaks in long-running processes, as reported in mswjs/msw#2537.

The Fix

Call socket.removeAllListeners() in the close event handler before emitting the close event to the MockHttpSocket. This ensures all listeners attached to the original socket are properly cleaned up.

.on('close', (hadError) => {
  // Remove all listeners from the original socket to prevent memory leaks.
  // @see https://github.com/mswjs/msw/issues/2537
  socket.removeAllListeners()
  this.emit('close', hadError)
})

Test

Added a regression test that makes many passthrough requests and verifies no MaxListenersExceededWarning is emitted.

Fixes mswjs/msw#2537

When passthrough mode is used, the MockHttpSocket attaches event listeners
to the original socket but never removes them when the socket closes.
This causes memory leaks, especially noticeable in long-running processes
with Node.js 20+.

This fix calls socket.removeAllListeners() in the close event handler
to properly clean up all listeners attached to the original socket.

Fixes mswjs/msw#2537
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Memory leak with Node.js 20+

1 participant