npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

promise-leak

v2.0.2

Published

Dev-mode runtime detection of unhandled/floating promises in Node.js

Readme

promise-leak

npm version Node License: MIT TypeScript

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-dev

Quick 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.js

Programmatic 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 --arg2

promise-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 for new 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/register in production, or guard it: if (process.env.NODE_ENV !== 'production') require('promise-leak/register').
  • Global Promise: When you call install() or use require('promise-leak/register'), the library replaces globalThis.Promise with a subclass so it can observe every new Promise(...). That’s the only global mutation; call uninstall() or detector.stop() to restore the original Promise.

Build

npm run build

This runs tsc and emits dist/ (JS + declaration files).

License

MIT