promise-leak
v2.0.2
Published
Dev-mode runtime detection of unhandled/floating promises in Node.js
Maintainers
Readme
promise-leak
Runtime detection of unhandled/floating promises in Node.js — not just rejections, but promises that are created and never awaited or .catch()-ed (the "fire and forget" pattern that silently swallows errors).
Trust: No network calls. No global mutation except when you opt in via register. Zero runtime dependencies. Built output is in dist/ (CommonJS + .d.ts).
Why promise-leak?
Node’s unhandledRejection is not enough. It only fires when a promise rejects and no handler has been attached. It does not fire when a promise is never awaited and resolves silently — or when you forget to handle it at all and it rejects later in a different tick. “Fire and forget” code like this is invisible to unhandledRejection until it actually rejects:
// Bug: promise is never awaited. If saveUser() rejects, the error is swallowed.
function handleRequest(req, res) {
saveUser(req.body); // floating promise
res.send({ ok: true });
}Why this is dangerous: In production, that can mean lost writes, inconsistent state, or errors that never surface. You only see the symptom (e.g. “user said they clicked Save but data didn’t persist”) with no stack trace.
How promise-leak helps: It temporarily replaces Promise so every newly created promise is tracked. After a short TTL (e.g. 100 ms), any promise that was never awaited or chained is reported with a stack trace pointing to the call site. So you see exactly where the leak is, in dev or CI, without waiting for a real rejection.
Intended for: Development and CI. Not for production (see Overhead).
Install
npm install promise-leak --save-devQuick start
At the very top of your entry file (before any other requires):
require('promise-leak/register');
// or
import 'promise-leak/register';This opts into replacing the global Promise with a tracked subclass until the process exits (or you call uninstall()). See Overhead & disabling for details.
Or run your app with Node’s -r flag:
node -r promise-leak/register server.jsProgrammatic API
import {
PromiseLeak,
intentional,
forget,
track,
createTestDetector,
runWithLeakCheck,
} from 'promise-leak';
const detector = new PromiseLeak({
ttl: 100,
stackDepth: 10,
ignore: [/node_modules/], // string | RegExp | (leak: LeakEntry) => boolean
onLeak: (leak) => { /* custom handler */ },
mode: 'warn', // 'warn' | 'throw' | 'silent' | 'strict'
groupBy: 'location', // 'location' | 'stack' | 'none'
maxLeaks: Infinity,
});
detector.start();
// Intentionally fire-and-forget (suppress report):
intentional(sendAnalytics());
forget(somePromise); // same as intentional()
// Track promises from native APIs (e.g. fetch) after install():
track(fetch('/api'));
// Teardown
detector.stop();
const report = detector.getReport();
detector.reset();
// Tests: strict preset
const testDetector = createTestDetector(); // mode: 'throw', short ttl, ignore: [/node_modules/]
// CLIs / scripts: fail if there are leaks
await runWithLeakCheck(async () => {
// your script logic here
});Reporting
Option A – use built-in reporters as onLeak callbacks:
import { PromiseLeak, reportToConsole, reportAsJson, reportSummary } from 'promise-leak';
// Full formatted message (same as default warn)
new PromiseLeak({ onLeak: reportToConsole, mode: 'silent' });
// One JSON object per leak (for CI / log aggregators)
new PromiseLeak({ onLeak: reportAsJson, mode: 'silent' });
// One short line per leak: file:line:column (functionName)
new PromiseLeak({ onLeak: reportSummary, mode: 'silent' });Option B – set reporter in options (only applies when mode: 'warn'):
new PromiseLeak({ mode: 'warn', reporter: 'json' }); // log JSON per leak
new PromiseLeak({ mode: 'warn', reporter: 'summary' }); // log one line per leak
new PromiseLeak({ mode: 'warn', reporter: 'console' }); // default: process.emitWarning| Reporter | Output |
|-----------|--------|
| console | Full formatted message (stack, location, tip). |
| json | One JSON-serializable object per leak. |
| summary | One line per leak: file:line:column (functionName). |
HTTP / Express-style middleware
import express from 'express';
import { createLeakMiddleware } from 'promise-leak';
const app = express();
app.use(createLeakMiddleware({ groupBy: 'location' }));Each request is checked after it finishes; any floating promises are logged (or cause an error if mode: 'throw').
CLI
After installing globally or as a dev dependency, you can run scripts via:
npx promise-leak run path/to/script.js --arg1 --arg2promise-leak will preload the detector, run your script, and exit non‑zero if any floating promises are detected.
Test frameworks
Use promise-leak/test (or promise-leak/jest) in any framework. Same API: an async after-each callback that fails the test if floating promises were detected.
import { promiseLeakAfterEach, promiseLeakStop } from 'promise-leak/test';
afterEach(promiseLeakAfterEach({ ttl: 50 }));
afterAll(promiseLeakStop); // or after() in Mocha| Framework | Hook it in |
|-----------|------------|
| Jest | afterEach(promiseLeakAfterEach()); afterAll(promiseLeakStop); |
| Vitest | Same as Jest. |
| Playwright | test.afterEach(promiseLeakAfterEach()); test.afterAll(promiseLeakStop); |
| Cypress | afterEach(promiseLeakAfterEach()); after(promiseLeakStop); |
| Mocha | afterEach(promiseLeakAfterEach()); after(promiseLeakStop); |
| Ava | test.afterEach() / test.after() with the same callbacks. |
| Node (node:test) | test.afterEach() / test.after() with the same callbacks. |
Any runner that exposes after-each and after-all (or equivalent) hooks can use the same pattern. Or wire createTestDetector() yourself: start in beforeAll, in afterEach wait TTL + a few ms, call detector.getReport(), throw if non‑empty, then detector.reset(), and detector.stop() in afterAll.
What gets reported
A leak is a promise that, within the TTL window, was never:
- awaited
- chained with
.then()or.catch()or.finally() - passed into
Promise.all/Promise.race/Promise.allSettled/Promise.any
So “fire and forget” calls like saveToDb(data) without await or .catch() are reported with a stack trace.
Example output
When leaks are detected you get a clear report and location:
(node:12345) [PROMISE_LEAK] PromiseLeak: [promise-leak] Floating promise detected
Created: 105ms ago
Location: src/services/user.ts:48:3 (saveUser)
State at detection: pending
Stack trace:
at saveUser (src/services/user.ts:48:3)
at handleRequest (src/routes/users.ts:22:5)Or with the CLI / runWithLeakCheck:
Error: Detected 3 floating promise(s):
src/services/user.ts:48:3 (saveUser)
src/jobs/sync.ts:102:1
src/workers/email.ts:31:5 (sendBatch)Comparison
| Tool | Detects rejections | Detects floating promises |
|------|--------------------|----------------------------|
| Node unhandledRejection | ✔ | ✘ |
| ESLint no-floating-promises | ✔ (static only) | ✘ (runtime edge cases, dynamic code) |
| promise-leak | ✔ | ✔ (runtime, all code paths) |
Static analysis can't see promises created in callbacks, conditionals, or third-party code. promise-leak runs in Node and observes every new Promise (and track()-ed native promises), so it catches leaks that lint rules miss.
Types
LeakEntry– one detected leak (id, stack, location, promiseState, etc.)PromiseLeakOptions– options fornew PromiseLeak(options)LeakMode,StackLocation– as needed
Overhead & disabling
Promise tracking adds some overhead (extra bookkeeping per promise, timers, stack capture). Use in development and CI only; do not enable in production.
- Disable quickly: Don’t load
promise-leak/registerin production, or guard it:if (process.env.NODE_ENV !== 'production') require('promise-leak/register'). - Global Promise: When you call
install()or userequire('promise-leak/register'), the library replacesglobalThis.Promisewith a subclass so it can observe everynew Promise(...). That’s the only global mutation; calluninstall()ordetector.stop()to restore the originalPromise.
Build
npm run buildThis runs tsc and emits dist/ (JS + declaration files).
License
MIT
