New Sep 19, 2024

Cancel Backend Processing in Node.js When Client-Side Aborts Request (MERN Stack)

Libraries, Frameworks, etc. All from Newest questions tagged reactjs - Stack Overflow View Cancel Backend Processing in Node.js When Client-Side Aborts Request (MERN Stack) on stackoverflow.com

Overview I am working on a MERN stack application, and I need help handling request cancellations in my Node.js backend, particularly when a client-side request is aborted.

Details In my application, users can trigger long-running processes in the backend, such as fetching large datasets from a MongoDB database using Mongoose or processing data in chunks. However, if the user navigates away from the page or aborts the request (e.g., by refreshing or closing the browser tab), the backend still continues processing the request. This leads to unnecessary resource usage, such as CPU time, memory, and database connections.

Expectations I would like to handle the situation where the client-side request is aborted (for instance, through AbortController in the frontend), and stop the corresponding processing on the Node.js backend immediately. I’m looking for a global solution that can handle this across all my Express.js controllers and cancel ongoing operations (e.g., database queries or data processing) efficiently

What I’ve Tried:

  1. Listening for the close event on the req object: I know that Express emits a close event when the connection is aborted, so I tried listening for this event and aborting operations manually. However, it’s not clear how to handle this properly when using Mongoose queries or other async operations.

  2. Mongoose Cursors: I attempted to use Mongoose cursors, as they allow fetching data in chunks and seem to support cancellation. But I’m not sure if this is the best approach, especially for all types of long-running operations.

Scroll to top