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

payload-stock-alerts

v1.0.0

Published

Low stock thresholds, admin notification on the downward crossing and backorder handling for Payload ecommerce.

Readme

payload-stock-alerts

npm node license payload

Tells the shop once, by email, when a product or variant falls to its low stock threshold, decides whether inventory may go below zero, and exposes both as data a storefront can read.

  • Works with @payloadcms/plugin-ecommerce and with any collection that has an inventory field
  • Sends through payload.sendEmail, so it uses whatever email adapter the project already has
  • No runtime dependencies and no mail library. The only import in the built file is APIError from payload itself, which is already a peer dependency
  • No admin components, so it survives minor releases

Install

Requires Payload 3.88 or newer and @payloadcms/plugin-ecommerce 3.88 or newer. Verified against Payload 3.88.0 with the official plugin installed.

pnpm add payload-stock-alerts
import { stockAlertsPlugin } from 'payload-stock-alerts'

export default buildConfig({
  plugins: [
    stockAlertsPlugin({
      threshold: 5,
      to: '[email protected]',
    }),
  ],
})

Everything currently low, as data:

import { findLowStock } from 'payload-stock-alerts'

const { alerts, scanned, truncated } = await findLowStock({ req })

or over HTTP, GET /api/stock-alerts/low-stock:

{
  "alerts": [
    {
      "allowBackorder": false,
      "collection": "variants",
      "id": "12",
      "inventory": 2,
      "status": "low-stock",
      "threshold": 5,
      "title": "Blue mug, large"
    }
  ],
  "scanned": 148,
  "truncated": false
}

What was measured

Why a product hook is not enough

Read from @payloadcms/[email protected], endpoints/confirmOrder.ts. After a payment settles, inventory is decremented like this:

await payload.db.updateOne({
  id,
  collection: variantsSlug,
  data: { inventory: { $inc: item.quantity * -1 } },
})

payload.db.updateOne goes straight to the database adapter. It runs no collection hooks and no field validation. A plugin that only watches products and variants would never see a single sale.

So this plugin watches two places:

| Trigger | Sees | How the level after the change is known | | --- | --- | --- | | afterChange on products and variants | admin edits, imports, your own payload.update calls | read from the document | | afterChange on an order being created | sales through the official checkout | the current level of each item minus the quantity on the order |

The order path runs before the decrement, because the order is written first and the $inc loop runs after confirmOrder returns. The level after the sale is therefore calculated from the order, not observed on the item. Turn it off with checkOnOrder: false if your stock moves some other way.

Notifying once, not on every save

The crossing, not the level, decides. A save that leaves stock at 3 with a threshold of 5 sends nothing if the previous level was already at or below 5; only a fall from above the threshold to at or below it does. A date is then written to lowStockNotifiedAt, and it is cleared the first time stock returns above the threshold, which arms the next crossing. Both rules are covered by the test suite.

Options

| Option | Default | Meaning | | --- | --- | --- | | allowBackorder | false | Whether inventory may go below zero when an item does not say | | backorderFieldName | 'allowBackorder' | Per item backorder checkbox | | checkOnOrder | true | Also check the items of an order when the order is created | | disabled | false | Stops checking and notifying but keeps the fields, so the database keeps its shape | | enableVariants | true | Adds the fields and hooks to the variants collection | | endpointPath | '/stock-alerts' | Path below the Payload API route | | inventoryFieldName | 'inventory' | Field the level is read from | | isAdmin | 'admin' in req.user.roles | Who may call the endpoints | | maxItems | 5000 | Items one scan reads in total before stopping and reporting truncated | | notifiedFieldName | 'lowStockNotifiedAt' | Date field recording that the crossing was notified | | notify | true | Sends the email. Off keeps the fields, the flag and the endpoints | | ordersSlug | 'orders' | Slug of the orders collection | | pageSize | 100 | Items one scan reads at a time | | productsSlug | 'products' | Slug of the products collection | | renderEmail | plain text list | Builds the subject and body from the alerts | | statusFieldName | 'stockStatus' | Read only virtual field carrying the status | | threshold | 5 | Threshold used when an item does not carry its own | | thresholdFieldName | 'lowStockThreshold' | Per item threshold field | | to | none | Address or addresses the notification goes to | | variantsSlug | 'variants' | Slug of the variants collection |

A value that cannot be used is replaced by its default rather than being applied. A negative threshold becomes 5 and 4.9 becomes 4. An entry in to without an @ is dropped. Nothing is silently reinterpreted: -5 never becomes 5.

What it adds to your database

| Collection | Field | Type | Notes | | --- | --- | --- | --- | | your products collection | lowStockThreshold | number | empty means the store default | | your products collection | allowBackorder | checkbox | defaults to the store setting | | your products collection | lowStockNotifiedAt | date | hidden, written by the plugin | | your products collection | stockStatus | text, virtual | in-stock, low-stock, out-of-stock or backorder. Computed on read, never stored | | your variants collection | the same four | | omitted when enableVariants is false |

Nothing else is created. No collection is added.

Two endpoints are added: GET /api/stock-alerts/low-stock, which only reports, and POST /api/stock-alerts/check, which reports and notifies for everything not yet flagged. Both are guarded by isAdmin.

Exported for server side use: stockAlertsPlugin, findLowStock, checkStock, stockStatus, crossedDown, decideNotification, defaultRenderEmail, resolveConfig.

stockStatus is what a storefront reads to show "on backorder": it is on every product and variant document returned by the API, and it already accounts for the per item allowBackorder setting.

Honest limits

Backorder cannot be refused on the checkout path. allowBackorder: false is enforced by a beforeValidate hook, so it refuses a negative level on every write that goes through Payload. It cannot refuse the official plugin's payload.db.updateOne, which bypasses hooks and validation entirely, so a sale can still drive inventory negative. The plugin reports that as out-of-stock; holding stock at checkout time is a different job and belongs in payload-stock-reservation.

The order path predicts, it does not observe. It calculates current level - quantity ordered. If the sale later fails to decrement, or something else changed the level in between, the number in the email is wrong by that difference. The level in GET /api/stock-alerts/low-stock is always read fresh and is never predicted.

Two simultaneous crossings can send two emails. Two concurrent writes both reading a pre-crossing level both decide to notify. The lowStockNotifiedAt flag narrows the window but does not close it, because the flag is read before it is written. The cost is a duplicate email, never a missed one.

Stock that is already low when you install stays quiet. There is no crossing to observe. Run POST /api/stock-alerts/check once after installing; it notifies for everything below threshold that carries no flag, and flags it.

A scan reads two indexes, not the whole catalogue. It asks for items whose inventory is at or below the store threshold, plus every item carrying its own threshold field, then filters each against its own value. A catalogue where most items carry a custom threshold is read almost in full. Pages are pageSize at a time and the scan stops at maxItems, reporting truncated: true.

Notification failure never breaks a save. Every send and every flag write is wrapped; failures are logged through payload.logger and the document is returned unchanged. Without to nothing is sent and a warning is logged instead.

stockStatus is virtual. It is computed by an afterRead hook and no column or property is created for it. It cannot be sorted or filtered on in a query.

License

MIT. Copyright George Vasiliades, https://github.com/Poseidonas