Adds five collections to Payload (products, categories, orders, carts and coupons) with default access rules that limit management to admins. A getEcommerce helper handles carts, order creation from a cart, coupon validation and product queries on the server. Requires Payload 3.37 or later plus users and media collections. Payments, emails and shipping rates are not included.
PayloadCMS plugin for e-commerce functionality - products, orders, carts, and checkout
Installation
npm i @xtr-dev/payload-ecommerce2
Stars
0
Forks
0
Open Issues
1 weeks ago
Last Updated
962
Weekly Downloads
v0.3.0
npm Version
455.0 KB
Unpacked Size
0
Dependencies
2+1 since Sep 6
| Date | Stars |
|---|---|
| Dec 5, 2026 | 2 |
| Dec 4, 2026 | 2 |
| Dec 3, 2026 | 2 |
| Dec 2, 2026 | 2 |
| Dec 1, 2026 | 2 |
| Nov 30, 2026 | 2 |
| Nov 29, 2026 | 2 |
| Nov 28, 2026 | 2 |
| Nov 27, 2026 | 1 |
| Nov 26, 2026 | 1 |
| Nov 25, 2026 | 1 |
| Nov 24, 2026 | 1 |
| Nov 23, 2026 | 1 |
| Nov 22, 2026 | 1 |
| Nov 21, 2026 | 1 |
| Nov 20, 2026 | 1 |
| Nov 19, 2026 | 1 |
| Nov 18, 2026 | 1 |
| Nov 17, 2026 | 1 |
| Nov 16, 2026 | 1 |
| Nov 15, 2026 | 1 |
| Nov 14, 2026 | 1 |
| Nov 13, 2026 | 1 |
| Nov 12, 2026 | 1 |
| Nov 11, 2026 | 1 |
| Nov 10, 2026 | 1 |
| Nov 9, 2026 | 1 |
| Nov 8, 2026 | 1 |
| Nov 7, 2026 | 1 |
| Nov 6, 2026 | 1 |
| Nov 5, 2026 | 1 |
| Nov 4, 2026 | 1 |
| Nov 3, 2026 | 1 |
| Nov 2, 2026 | 1 |
| Nov 1, 2026 | 1 |
| Oct 31, 2026 | 1 |
| Oct 30, 2026 | 1 |
| Oct 29, 2026 | 1 |
| Oct 28, 2026 | 1 |
| Oct 27, 2026 | 1 |
| Oct 26, 2026 | 1 |
| Oct 25, 2026 | 1 |
| Oct 24, 2026 | 1 |
| Oct 23, 2026 | 1 |
| Oct 22, 2026 | 1 |
| Oct 21, 2026 | 1 |
| Oct 20, 2026 | 1 |
| Oct 19, 2026 | 1 |
| Oct 18, 2026 | 1 |
| Oct 17, 2026 | 1 |
| Oct 16, 2026 | 1 |
| Oct 15, 2026 | 1 |
| Oct 14, 2026 | 1 |
| Oct 13, 2026 | 1 |
| Oct 12, 2026 | 1 |
| Oct 11, 2026 | 1 |
| Oct 10, 2026 | 1 |
| Oct 9, 2026 | 1 |
| Oct 8, 2026 | 1 |
| Oct 7, 2026 | 1 |
| Oct 6, 2026 | 1 |
| Oct 5, 2026 | 1 |
| Oct 4, 2026 | 1 |
| Oct 3, 2026 | 1 |
| Oct 2, 2026 | 1 |
| Oct 1, 2026 | 1 |
| Sep 30, 2026 | 1 |
| Sep 29, 2026 | 1 |
| Sep 28, 2026 | 1 |
| Sep 27, 2026 | 1 |
| Sep 26, 2026 | 1 |
| Sep 25, 2026 | 1 |
| Sep 24, 2026 | 1 |
| Sep 23, 2026 | 1 |
| Sep 22, 2026 | 1 |
| Sep 21, 2026 | 1 |
| Sep 20, 2026 | 1 |
| Sep 19, 2026 | 1 |
| Sep 18, 2026 | 1 |
| Sep 17, 2026 | 1 |
| Sep 16, 2026 | 1 |
| Sep 15, 2026 | 1 |
| Sep 14, 2026 | 1 |
| Sep 13, 2026 | 1 |
| Sep 12, 2026 | 1 |
| Sep 11, 2026 | 1 |
| Sep 10, 2026 | 1 |
| Sep 9, 2026 | 1 |
| Sep 8, 2026 | 1 |
| Sep 7, 2026 | 1 |
| Sep 6, 2026 | 1 |
Trends appear once the first and last snapshots are 7 days apart. Collecting since Nov 29 — 7 daily snapshots so far.
Each point is npm's rolling 7-day download count.
Health Score
Composite score based on GitHub activity, stars, npm downloads, publish recency, dependency count, and package size.
Badge for your README
[](https://payloaddirectory.dev/plugins/1089791699-root)<a href="https://payloaddirectory.dev/plugins/1089791699-root"><img src="https://payloaddirectory.dev/badge/1089791699-root.svg" alt="Payload Directory"></a>README
Products, carts, orders and coupons for PayloadCMS 3.x, with server-side helpers
v0.x — minor versions may contain breaking changes until 1.0.
calculateTax hook you implement (fixed rate, per region, or a call to a tax service)getEcommerce(payload) for carts, orders, coupons and products on the serverNot included: payment processing, emails and shipping rates. Payments are shown in the demo app with @xtr-dev/payload-billing; see Not included.
pnpm add @xtr-dev/payload-ecommerce
Requires payload ^3.37.0. The plugin is developed and tested on Payload 3.94 (Next.js 16), and CI also runs the tests on 3.37, with SQLite, MongoDB and Postgres.
import { payloadEcommerce } from '@xtr-dev/payload-ecommerce'
export default buildConfig({
plugins: [
payloadEcommerce({
// All options are optional; see "Options" below
}),
],
})
The plugin adds the five collections below. Orders and carts relate to your users collection and product images to your media collection; your config has to provide both (users and media unless you set userCollection / mediaCollection).
| Option | Default | What it does |
|---|---|---|
collections.products / categories / orders / carts / coupons | default slugs | A string renames the collection; a function extends it (see Extending Collections) |
userCollection | 'users' | Auth collection the user field of orders and carts relates to, and whose users own their carts and orders |
mediaCollection | 'media' | Upload collection product images relate to |
isAdmin | role === 'admin' or roles includes 'admin' | Who manages the shop (see Access control) |
roundMoney | two decimals | Rounds the discount, tax and total the plugin calculates; pass Math.round for integer cents (see Money) |
cartCleanupTask | false | true registers the jobs task that deletes expired carts; { schedule } also schedules it (see Carts) |
hooks.calculateTax | – | Returns the tax of an order (see Tax Configuration) |
hooks.beforeCreateOrder | – | Receives and returns the data of a new order, after coupon and tax and before the total is computed |
hooks.afterCreateOrder | – | Runs after a new order took its stock; throwing fails the order |
disabled | false | Keeps the collections (fields and access rules, so the database schema does not change) but removes the plugin's collection hooks and does not register the cart cleanup task |
Renaming works everywhere: relationships between the collections, hooks and the server helpers all follow the configured slugs, so getEcommerce(payload) needs no slug arguments. getEcommerceSlugs(payload) returns the slugs in use.
The collections are locked down by default: only an admin can manage them, and by default an admin is a user with role: 'admin'. Read Access control before you open the admin panel.
Every collection gets access rules, which apply to REST, GraphQL, the admin panel and Local API calls made with overrideAccess: false:
| Collection | Everyone | Signed-in user | Admin |
|---|---|---|---|
| products | read active products | same | read and write all |
| categories | read | same | read and write all |
| coupons | – | – | read and write all |
| orders | – | read their own (user is them) | read and write all |
| carts | – | read, create and update their own (user is them) | read and write all |
sessionId) and guest orders are not reachable through the API without an admin. A storefront reaches them on the server through getEcommerce(payload).createOrderFromCart), not by customers through the API: whoever creates an order decides its prices.ecommerce.coupons.validateCoupon.user and sessionId after it is created.accessToken is not readable or writable through the API by anyone, admins included (see Order access tokens).userCollection (default 'users').Who is an admin is decided by the isAdmin option. The default accepts a signed-in user whose role is 'admin' or whose roles array contains 'admin'. If your users collection has neither field, nobody is an admin and the collections cannot be managed until you pass your own check:
payloadEcommerce({
// Everyone in a separate `admins` auth collection manages the shop
isAdmin: ({ req }) => req.user?.collection === 'admins',
})
If you rely on a role field, protect it with field access so customers cannot change their own role.
To change a rule for one collection, set access in a collection extender; it receives the collection with the defaults already applied:
payloadEcommerce({
collections: {
products: (base) => ({ ...base, access: { ...base.access, read: () => true } }),
},
})
inventory.trackQuantity, inventory.quantity). inventory.lowStockThreshold is a plain field for your own use; the plugin sends no low-stock alertsecommerce.products.getProducts({ search }) looks for the text in the title and the SKU. On SQLite it also matches the description; on Postgres it does not, because the description is rich text, which Postgres stores as jsonb and cannot match against text.
state and postalCode are optional, since not every country has them) and an optional billing addressuser, and a customerEmail to reach the customer of a guest orderaccessToken generated by the plugin, for a link that lets a guest see their order (see Order access tokens)paymentStatus, paymentMethod, paymentId) that your payment integration sets; the plugin takes no payments and sends no emailsparent category. The plugin stores the relationship only; building a tree or breadcrumb from it is up to youUse the getEcommerce helper for server-side operations:
getEcommercewas calleduseEcommercein 0.1.0. The old name still works but is deprecated: it is not a React hook, and theuseprefix makes thereact-hooks/rules-of-hookslint rule reject calls from server actions and route handlers.
import { getPayload } from 'payload'
import { getEcommerce } from '@xtr-dev/payload-ecommerce'
const payload = await getPayload({ config })
// Trusted server code: bypasses access control (see "Helpers and access control" below)
const ecommerce = getEcommerce(payload)
// Add to cart
await ecommerce.cart.addToCart({
sessionId: 'session-123',
productId: 'product-id',
quantity: 2,
variant: 'Medium', // optional; the `name` of one of the product's variants
})
// Create order from cart
const order = await ecommerce.orders.createOrderFromCart({
cartId: 'cart-id',
orderData: {
shippingAddress: { /* ... */ },
billingAddress: { /* ... */ },
paymentMethod: 'credit_card',
shipping: 5,
couponCode: 'SAVE10', // optional; validated and applied by the plugin
},
})
// Preview a coupon (see "Coupons" below)
const result = await ecommerce.coupons.validateCoupon({
code: 'SAVE10',
cartTotal: 100,
productIds: ['product-1', 'product-2'],
})
createOrderFromCart takes everything about the order in orderData; shippingAddress is the only required part. (0.2.0 and earlier also read shippingAddress, billingAddress, paymentMethod and notes next to cartId; those are no longer read.)
Document ids are strings on MongoDB and numbers on SQLite and Postgres. Every helper accepts both, and converts an id to the type its collection uses, so a numeric id that arrives as text ('5' from a URL, a form or a JSON body) works on SQL databases. toDocumentId(payload, collectionSlug, id) is exported for your own Local API calls. A relationship field holds either a bare id or the populated document, depending on depth. Use the exported getRelationshipId to read the id in both cases:
import { getRelationshipId } from '@xtr-dev/payload-ecommerce'
const productIds = cart.items.map((item) => getRelationshipId(item.product))
With generated types and the default collection slugs, the helpers return your generated document types without casts:
const cart = await ecommerce.cart.getCart(user.id) // Cart | null
const order = await ecommerce.orders.createOrderFromCart({ cartId, orderData }) // Order
const { docs } = await ecommerce.products.getProducts() // Product[]
const result = await ecommerce.coupons.validateCoupon({ code, cartTotal })
if (result.valid) {
result.coupon // Coupon
} else {
result.reason // CouponRefusalReason
result.coupon // Coupon | undefined
}
The types are those of your collections named carts, coupons, orders and products. If you renamed a collection, name its type yourself; collections you leave out keep the default:
import type { ShopCart, ShopOrder } from './payload-types'
const ecommerce = getEcommerce<{ carts: ShopCart; orders: ShopOrder }>(payload)
Do the same when one of those four slugs belongs to a collection of your own that is not the plugin's, because the default would be that collection's type. Without generated types, and for a renamed collection without a type argument, documents are untyped (JsonObject & TypeWithID).
getCart, findCouponByCode and getOrderByToken return null when there is nothing to find. getOrder and getProduct throw Payload's NotFound instead. The helper types are exported as EcommerceHelpers, CartHelpers, OrderHelpers, CouponHelpers, ProductHelpers and ApplyCouponResult; each takes the document type as a type argument.
getEcommerce(payload) bypasses the collections' access rules (overrideAccess: true). That is what a storefront needs for guest carts and for creating orders, and it means your server code decides whose cart or order is touched: only pass ids (userId, sessionId, cartId, orderId) that belong to the visitor, for example a session id read from your own cookie.
To have the helpers enforce the access rules for a signed-in user instead, pass the user (or the request) with overrideAccess: false:
const ecommerce = getEcommerce(payload, { overrideAccess: false, user })
// or: getEcommerce(payload, { overrideAccess: false, req })
await ecommerce.cart.getCart(user.id) // their cart
await ecommerce.orders.getOrder(orderId) // throws unless it is their order
In that mode cart, order and product reads, cart changes and updateOrderStatus run as that user. createOrderFromCart reads the cart as the user, so it only works on their own cart, and then creates the order with full access. Coupon validation and the inventory helpers always run with full access. A req passed without overrideAccess: false is only used to join its transaction.
A cart belongs to a user (userId) or to a guest session (sessionId, any string you keep in a cookie). An order created from a guest cart has no user, so pass the address to reach the customer at:
const cart = await ecommerce.cart.addToCart({ sessionId, productId, quantity: 1 })
const order = await ecommerce.orders.createOrderFromCart({
cartId: cart.id,
orderData: {
customerEmail: '[email protected]', // stored on the order as `customerEmail`
shippingAddress: { firstName, lastName, address1, city, country }, // state and postalCode optional
},
})
customerEmail is optional and can also be set on the order of a signed-in user. The billing address defaults to the shipping address. Guest carts and guest orders are only reachable through these helpers or as an admin (see Access control). To show a guest their order afterwards, use its access token.
A guest has no account to sign in to, so the default access rules give them no way back to their order, and an order id or number is too easy to guess to serve as a key on its own. Every order therefore gets an accessToken when it is created: 32 random bytes as 43 URL-safe characters. Put it in the link you give the customer (the confirmation redirect, the confirmation email), and look the order up with it:
const order = await ecommerce.orders.createOrderFromCart({ cartId, orderData })
redirect(`/orders/${order.orderNumber}?token=${order.accessToken}`)
// On the order page, with values straight from the URL:
const order = await ecommerce.orders.getOrderByToken({ orderNumber, token }) // or { orderId, token }
if (!order) notFound()
getOrderByToken returns the order (relationships populated, depth 2) only when the token is that order's token, and null otherwise. A wrong token, an order that does not exist, an order without a token and input that is not a string all give the same null, so order numbers cannot be probed, and the token is compared in constant time. Pass exactly one of orderId and orderNumber. It reads with full access also for helpers created with overrideAccess: false, because holding the token is the permission; combine it with your own check when signed-in customers or admins should reach the page without a token.
About the field:
where filter through REST, GraphQL, the admin panel or the Local API with overrideAccess: false, by admins either. Server code reads it with the Local API's default overrideAccess: true: the order createOrderFromCart returns, payload.create, payload.findByID. An order document read that way contains the token, so pick fields before sending one to a browser that is not the customer's.getOrderByToken. If you need links for them, write your own values to accessToken in a migration, directly through the database adapter.matchesOrderAccessToken(order, token) is exported for comparing in constant time against an order you already loaded.The plugin stores amounts as plain numbers and does not care whether they are major units (19.99) or integer minor units (1999 cents), as long as you use one of them everywhere. What it calculates itself — a cart's subtotal, the line totals and subtotal of an order made with createOrderFromCart, a coupon's discount, the result of your calculateTax hook and the order total — it rounds with the roundMoney option:
payloadEcommerce({
roundMoney: Math.round, // prices in integer cents: 10% of 1995 is 200, not 199.5
})
The default rounds to two decimals, which suits prices in major units. Amounts you pass in yourself (prices, shipping, a manual discount) are stored as given. getRoundMoney(payload) returns the configured function.
A cart or order line is identified by its product and, optionally, the name of one of that product's variants. One function decides what a unit costs, and the cart subtotal and createOrderFromCart both use it:
import { resolveUnitPrice } from '@xtr-dev/payload-ecommerce'
resolveUnitPrice(product) // product.price
resolveUnitPrice(product, 'Large') // the variant's own price when it has one, else product.price
A variant price of 0 is a real price (a free variant); leave the field empty to use the product's price. A variant name the product does not have is priced at the product's price. Use the same function wherever your storefront shows a line price, so it matches the subtotal.
A cart holds one line per product + variant combination, so two variants of one product are two lines. addToCart, updateCartItem and removeFromCart all take the variant to say which line is meant; leaving it out means the line without a variant, never "any line of this product":
// Sets the quantity of the "Medium" line only (0 or less removes that line)
await ecommerce.cart.updateCartItem({ cartId, productId, variant: 'Medium', quantity: 3 })
// Removes the "Medium" line only
await ecommerce.cart.removeFromCart({ cartId, productId, variant: 'Medium' })
updateCartItem throws Item not found in cart when the cart has no line for that combination. The exported isSameCartLine(item, productId, variant) is the comparison the helpers use.
The /dev directory holds a Next.js storefront built on the plugin:
The demo's cart and checkout API routes are part of the demo, not of the plugin.
Run the demo:
git clone https://github.com/xtr-dev/payload-ecommerce.git
cd payload-ecommerce
pnpm install
pnpm dev
Visit http://localhost:3000
Pass a function to extend a collection with custom fields, hooks or access rules. It may also return another slug to rename the collection. The function is called twice while the config is built, so it should only return a new collection and have no side effects:
payloadEcommerce({
collections: {
products: (baseConfig) => ({
...baseConfig,
fields: [
...baseConfig.fields,
{
name: 'brand',
type: 'text',
},
],
}),
},
})
Products and categories have a unique slug. Leave it empty and it is generated from the product's title or the category's name ("Café Crème 250g" → cafe-creme-250g); when that slug is already taken, a number is appended (blue-shirt-2, blue-shirt-3, …). A slug you enter yourself is kept as entered and is not regenerated when the title changes; if it is already in use, the save is rejected with a validation error on slug. Clear the slug to have it generated again. slugify is exported.
A cart belongs to a user (userId) or a guest session (sessionId) and expires 30 days after it was last changed: every change to a cart moves expiresAt to 30 days from now, unless the change sets expiresAt itself.
The cart helpers treat an expired cart as absent: getCart returns null, addToCart starts a new cart, updateCartItem / removeFromCart / clearCart throw Cart not found, and createOrderFromCart throws Cart has expired.
Expired carts stay in the database until you delete them. Nothing does that on its own; pick one:
import { deleteExpiredCarts } from '@xtr-dev/payload-ecommerce'
// From your own cron job, script or endpoint
const { deleted } = await deleteExpiredCarts(payload)
// Or as a Payload jobs task: opt in, then queue it from your schedule
payloadEcommerce({ cartCleanupTask: true })
await payload.jobs.queue({ task: 'ecommerce-delete-expired-carts', input: {} })
// Or let Payload queue the task on a schedule (needs a Payload version with task schedules)
payloadEcommerce({
cartCleanupTask: { schedule: [{ cron: '0 3 * * *', queue: 'nightly' }] },
})
With true the task is only registered, not scheduled. With a schedule Payload queues it at those times, provided your jobs runner handles schedules for that queue (jobs.autoRun, or payload.jobs.handleSchedules() from your own cron). Either way it runs when your jobs runner processes the queue (jobs.autoRun, payload jobs:run or payload.jobs.run()). Task schedules are a feature of newer Payload releases (verified with 3.94); on a Payload version without them the schedule is ignored.
A coupon is applied by the plugin when an order is created with it. Pass the coupon's id as coupon (or its code as orderData.couponCode to createOrderFromCart); the orders collection then:
active, within validFrom/validUntil, usageCount below usageLimit, the customer's earlier orders with this coupon (cancelled and refunded ones excluded) below customerLimit (an order without a user cannot use a coupon that has a customerLimit), subtotal at least minPurchase, and at least one order item matching appliesToProducts / appliesToCategories when those are set. A limit of 0 or an empty restriction means no limit.coupon when a check fails. The error carries the refusal's reason (see When an order is rejected).discount — a percentage of the subtotal (capped by maxDiscount) or the fixed amount, rounded with roundMoney and never more than the subtotal. A discount passed together with a coupon is ignored.shipping to 0 for a freeShipping coupon (its discount is 0).usageCount, and gives that use back when the order is cancelled or refunded (see "Inventory and Order Side Effects"). The count is the plugin's to keep: an update through the admin panel, REST or GraphQL cannot change usageCount, so saving a coupon never overwrites uses counted in the meantime. To correct it yourself, update it through the Local API.Tax and total are calculated after that, so they include the coupon's effect. Without a coupon, the caller's discount is used as is. Changing the coupon of an existing order does not recalculate it.
To show the effect before ordering, use validateCoupon, which runs the same checks without using the coupon:
const result = await ecommerce.coupons.validateCoupon({
code: 'save10', // matched ignoring case; codes are stored in upper case
cartTotal: 100, // subtotal before discount, tax and shipping
userId, // the signed-in customer; a coupon with a customerLimit is refused without it
productIds, // needed for product-restricted coupons
categoryIds, // needed for category-restricted coupons
})
// { valid: true, discount: 10, freeShipping: false, coupon }
// { valid: true, discount: 0, freeShipping: true, coupon } for a free shipping coupon
// { valid: false, discount: 0, freeShipping: false, reason: 'expired', error: 'Coupon has expired', coupon }
A refusal has a reason to word your own message from. error is an English description meant for logs.
reason | The coupon is refused because |
|---|---|
not_found | no coupon has this code (the only refusal without coupon) |
inactive | its status is inactive |
not_yet_valid | validFrom is in the future |
expired | validUntil has passed, or its status is expired |
usage_limit | usageCount has reached usageLimit |
customer_required | it has a customerLimit and no userId was given, so the limit cannot be counted; ask the visitor to sign in |
customer_limit | the customer's orders with it have reached customerLimit |
min_purchase | cartTotal is below minPurchase; the result also has minPurchase, the stored amount, to format as your shop formats money |
not_applicable | it is restricted to products or categories and the cart has none of them |
The checks run in this order and the first one that fails is reported. error is Coupon has expired for both ways a coupon expires (0.2.0 said Coupon is not active for the status). The types are exported as ApplyCouponResult and CouponRefusalReason. coupon is the whole coupon document (usage count, limits, restrictions, your internal description), also on a refusal, so pick the fields you need before sending a result to the browser; dev/lib/couponPreview.ts in this repository shows one way.
A restricted percentage or fixed coupon discounts the whole subtotal once a matching product is in the order, not only the matching lines.
An order's total is always computed by the plugin when the order is saved:
total = subtotal − discount + tax + shipping
tax comes from the calculateTax hook when one is configured (rounded with roundMoney; a negative result is stored as 0). Without the hook it is the tax passed by the caller, or 0. A hook that fails makes the order fail (see Tax Configuration).total passed by the caller is ignored, so it can be left out. On update, tax is recalculated only when the items, subtotal, discount, shipping or an address actually differ from the stored order, and the total only when an amount differs. A status or tracking update, or re-saving an unchanged order in the admin UI, leaves both as they were.roundMoney.ecommerce.orders.calculateTotal({ subtotal, discount, tax, shipping }), which rounds the same way. The exported calculateOrderTotal(parts, roundMoney?) is the function behind it; without its second argument it only removes floating point noise.Configure automatic tax calculation using the calculateTax hook:
payloadEcommerce({
hooks: {
calculateTax: async (orderData) => {
// Access order information
const { items, subtotal, discount, shipping, shippingAddress, billingAddress } = orderData
// Implement your tax logic
const taxableAmount = subtotal - discount
const taxRate = 0.10 // 10%
// No need to round: the plugin rounds the result with `roundMoney`
return taxableAmount * taxRate
},
},
})
The hook receives:
items - Array of order items with product, quantity, and pricesubtotal - Order subtotal before tax/shippingdiscount - Discount amount (from coupons)shipping - Shipping costshippingAddress - Customer shipping addressbillingAddress - Customer billing addressExamples:
// Simple fixed rate
calculateTax: async ({ subtotal, discount }) => {
return (subtotal - discount) * 0.08875 // 8.875% NY tax
}
// Rate by state
calculateTax: async ({ subtotal, discount, shippingAddress }) => {
const rates = {
'CA': 0.0725,
'NY': 0.08875,
'TX': 0.0625,
}
const rate = rates[shippingAddress?.state] || 0
return (subtotal - discount) * rate
}
An order is never saved without the tax the hook was supposed to calculate. When calculateTax throws, or returns something that is not a finite number, the create or update fails with:
Order was not created: tax could not be calculated (<the hook's error message>)
(not updated for an update.) The hook's own error is on the thrown error's cause. Tax is calculated before anything is written, so a failed create leaves no order, takes no stock and counts no coupon use, createOrderFromCart leaves the cart as it was, and a failed update changes nothing — a cancellation in that same update does not happen either. The error is a server error (HTTP 500 through the REST API), not a validation error.
Because the hook only runs on an update that changes an item, amount or address, a status or tracking update still works while your tax service is down. If you would rather accept orders without tax in that case, catch the error inside your hook and return a fallback amount.
Products with inventory.trackQuantity have stock. A variant with its own inventory number is tracked separately; an order line without a variant, or for a variant whose inventory is empty, draws from the product's inventory.quantity. There is no backorder option: a tracked product cannot be ordered beyond its stock.
When an order is created (any status except cancelled / refunded):
items such as Not enough stock for "Blue Shirt" (variant "M"): 3 requested, 1 available. Lines for the same product are added up. The error also carries the product, variant and quantities as data (see When an order is rejected).usageCount is incremented, each with one conditional database statement, so concurrent orders cannot oversell the last units or take a coupon past its usageLimit. The order that loses such a race is rejected.afterCreateOrder hook runs.If any of these steps fails, the order is not created: inside a database transaction everything is rolled back, and on a database without transactions (the SQLite adapter's default) the plugin puts back what it took and deletes the order.
The order records what it holds in two read-only fields, inventoryReduced and couponUsageCounted. When its status changes to cancelled or refunded, the stock is put back and the coupon use is given back, once; later updates do nothing more. "Once" also holds when the order is cancelled and refunded at the same moment, or cancelled twice by a double submit: each flag is cleared with one conditional database statement, and only the update that clears it gives anything back. The flags are written when the order is created and by that statement only; an update never writes them, so a value passed by a caller is ignored. Not handled: editing the items of an existing order does not adjust stock, and reopening a cancelled order does not take stock again.
Limits:
[payload-ecommerce] No atomic … update …), because the statements use parts of the adapters that are not public API. The plugin's tests assert that the atomic statements are used on SQLite, MongoDB and Postgres on Payload 3.37 and 3.94; if you see the warning after a Payload upgrade, please open an issue.transactionOptions set) a database error halfway rolls the whole update back, the cancellation included, and it can simply be repeated. Without transactions (the SQLite adapter's default) nothing is rolled back: the update fails with the database's error, but the order is already cancelled, the stock of the lines before the failing one is back and the rest is not, and inventoryReduced is already cleared, so cancelling again restores nothing more. Compare the order's lines with the products' stock and correct the rest by hand (ecommerce.products.restoreInventory). The plugin cannot repair this itself: the lines live in different rows, so no single statement covers them, and undoing the lines already restored would need the same failing database and could itself fail or take units another order has bought since. Creating an order does not have this gap, because a new order can be deleted again; a cancellation that half happened cannot be taken back. Use a database with transactions if this matters to you.An order that is refused for its stock or its coupon fails with an OrderRejectedError, whether it was created with createOrderFromCart, the Local API, REST or the admin panel. It is a Payload ValidationError (HTTP 400, reported on items or coupon) whose message is the English reason, and it carries the cause as data, so you do not have to match on the text. getOrderRejection(error) returns that cause, or undefined for any other error:
import { getOrderRejection } from '@xtr-dev/payload-ecommerce'
try {
order = await ecommerce.orders.createOrderFromCart({ cartId, orderData })
} catch (error) {
const rejection = getOrderRejection(error)
if (!rejection) throw error // not a refusal: a missing address, a failing hook, the database
if (rejection.type === 'stock') {
// { type: 'stock', reason: 'out_of_stock', product, variant?, requested, available? }
return { error: 'Some items in your cart are sold out', product: rejection.product }
}
// { type: 'coupon', reason: CouponRefusalReason, minPurchase? }
return { error: couponMessages[rejection.reason] }
}
type | reason | Other fields |
|---|---|---|
stock | out_of_stock | product: id of the product that is short. variant: the variant's name, when the variant has its own stock number and that is what is short. requested: units the order asks for, added up over its lines for that stock. available: units in stock when the order was checked |
coupon | a CouponRefusalReason, the same value validateCoupon gives | minPurchase when the reason is min_purchase |
available is absent when the order passed the stock check and then lost the last units to a simultaneous order, because the number it read is out of date by then; read the product again if you want to show one. A coupon whose last use was taken the same way is rejected with usage_limit. createOrderFromCart with a couponCode that no coupon has is rejected with not_found.
The same object is on the error as error.rejection and error.data.rejection. Payload sends data in REST and GraphQL error responses, so a client of those can pass errors[0] of the response body to getOrderRejection. The types are exported as OrderRejection, StockOrderRejection and CouponOrderRejection, and the class as OrderRejectedError. getOrderRejection is the safer check of the two: instanceof fails when a bundler ends up with two copies of the plugin.
The helpers ecommerce.products.checkInventory, reduceInventory (throws when stock is short) and restoreInventory, and ecommerce.coupons.incrementCouponUsage / decrementCouponUsage use the same atomic statements, for stock movements that are not orders. They take an optional { req } as last argument to run inside a transaction.
paymentStatus, shipping and the like from your own integration (the demo uses @xtr-dev/payload-billing).getEcommerce(payload) from your own server actions or route handlers, as the demo does.# Install dependencies
pnpm install
# Run demo with hot reload
pnpm dev
# Build the plugin
pnpm build
# Checks run by CI and before a release
pnpm typecheck # src, then the helper result types against the built declarations (dev/type-tests)
pnpm lint
pnpm test # integration tests (vitest) on a temporary SQLite database
pnpm test:mongo # the same tests on an in-memory MongoDB replica set
pnpm test:postgres # the same tests on a Postgres server, see below
pnpm test:pack # build, pack and import every published export
# The integration tests with a coverage report for src/
pnpm test:coverage
pnpm test:mongo downloads a MongoDB server binary on its first run (mongodb-memory-server). The demo itself runs on MongoDB when DATABASE_ADAPTER=mongodb and DATABASE_URI (a MongoDB connection string) are set; SQLite is the default.
pnpm test:postgres needs a running Postgres server and DATABASE_URI set to a connection string for it. The user must be allowed to create databases: each run creates two databases with a unique name and drops them afterwards, and writes nothing to the database named in the URI.
docker run --rm -d --name ecommerce-test-postgres -e POSTGRES_PASSWORD=postgres -p 127.0.0.1:5432:5432 postgres:16
DATABASE_URI=postgres://postgres:[email protected]:5432/postgres pnpm test:postgres
docker stop ecommerce-test-postgres
The demo runs on Postgres the same way, with DATABASE_ADAPTER=postgres and DATABASE_URI naming the database to use.
MIT © xtr.dev
ecommerce
Ecommerce utilities for Payload with idempotent Stripe confirmation, orders, carts and inventory handling
10019.0k/wk46.1kv3 v4
payload stock reservation
Validates variant stock and price at checkout and holds stock until payment settles or the hold expires
76152/wk1v3
payload coupons
Coupon codes with percentage and fixed discounts for Payload ecommerce, calculated in integer minor units
76144/wk2v3
payload fulfillment
Extra order states, transition history, internal notes and tracking fields for Payload ecommerce orders
7332/wk1v3
payload stock alerts
Low stock threshold alerts by email and backorder handling for Payload ecommerce products and variants
7222/wk1v3
payload shipping classes
Weight, dimensions and a shipping class on Payload products and variants, stored in one canonical unit
7210/wk2v3