AbortController is a browser / Web API used to cancel ongoing asynchronous operations, most commonly fetch requests.
const controller = new AbortController();
const signal = controller.signal;
fetch("/api/data", { signal });
controller.abort(); // cancels the request
🧠 What Happens When You Abort a Fetch?
- ❌ Browser stops listening to the response
- ❌ Promise rejects with
AbortError - ❌ Response is ignored by frontend
⚠️ Important:
👉 Backend API is NOT automatically canceled
❓ Does AbortController Cancel the Request on Backend?
❌ NO (By default)
- AbortController works only on the client
- Backend may still be processing
- Server does not know the client aborted unless explicitly handled
This is a very common interview trap.
🔍 Why Backend Still Runs?
- HTTP is stateless
- Once request reaches server, it continues
- Client abort ≠ server stop
✅ How to Cancel / Stop Work on Backend (Node.js)
You must explicitly handle client disconnects.
🔹 1️⃣ Detect Client Abort in Node.js (Express)
Using req.on("close")
app.get("/data", (req, res) => {
req.on("close", () => {
console.log("Client aborted request");
// cleanup logic here
});
// long-running task
});
✔ Detects client disconnect
✔ Allows cleanup / cancellation
🔹 2️⃣ Cancel Long-Running Tasks (Example)
app.get("/data", async (req, res) => {
let aborted = false;
req.on("close", () => {
aborted = true;
});
for (let i = 0; i < 10; i++) {
if (aborted) return;
await heavyTask();
}
res.send("Done");
});
🔹 3️⃣ Abort Database Queries (If Supported)
Some DBs support cancellation:
Example (MongoDB)
const session = client.startSession();
req.on("close", () => {
session.abortTransaction();
});
🔹 4️⃣ Using AbortController in Node.js (Node 16+)
Node also supports AbortController for:
- Fetch
- Streams
- Some DB drivers
const controller = new AbortController();
req.on("close", () => controller.abort());
🧪 Frontend + Backend Combined Flow
Frontend
const controller = new AbortController();
fetch("/api/data", { signal: controller.signal });
// on unmount
controller.abort();
Backend
req.on("close", () => {
console.log("Client disconnected");
});
🎯 Short Interview Answer
AbortControlleris used on the frontend to cancel ongoing requests likefetch. It only stops the client from waiting for the response and does not automatically cancel backend processing. To stop backend work, Node.js must listen for client disconnects usingreq.on("close")and manually cancel long-running tasks or database operations.
⭐ One-line summary
AbortController cancels the request on the client — backend cancellation must be handled explicitly.