Skip to content

[plugin-ecommerce] Variant hooks call findByID without req, so variants can't be created in the same transaction as their product #18338

Open

Description

@yasnikoy

Describe the Bug

In @payloadcms/plugin-ecommerce, two variant hooks look up the parent product with req.payload.findByID(...) without passing req, so the lookup runs outside the current transaction:

With a transactional adapter (Postgres), creating a product and its variants in the same transaction therefore fails: the product created earlier in the transaction isn't visible to these lookups, and the variant create throws NotFound. It works in the admin UI only because there the product is committed before variants are added.

Still present on main. The fix is to pass req to these findByID calls (other lookups in the same file, e.g. the variant options, have the same issue). The carts beforeChange hook that computes the subtotal (carts/beforeChange.ts) uses the same pattern.

Link to the code that reproduces this issue

https://github.com/payloadcms/payload/blob/v3.90.2/packages/plugin-ecommerce/src/collections/variants/createVariantsCollection/hooks/validateOptions.ts#L25

Reproduction Steps

With the ecommerce template (or any config using ecommercePlugin with variants enabled) on @payloadcms/db-postgres:

import { commitTransaction, createLocalReq, initTransaction } from 'payload'

const req = await createLocalReq({}, payload)
await initTransaction(req)

const product = await payload.create({
  collection: 'products',
  data: { title: 'Test', enableVariants: true, variantTypes: [variantTypeID] },
  req,
})

// Throws NotFound: the plugin's hooks read `products` outside the transaction
await payload.create({
  collection: 'variants',
  data: { product: product.id, options: [variantOptionID] },
  req,
})

await commitTransaction(req)

Expected: the variant is created. Actual: NotFound from validateOptions / the beforeChange hook.

Which area(s) are affected?

plugin: ecommerce, db: postgres

Environment Info

payload: 3.90.2
@payloadcms/plugin-ecommerce: 3.90.2
@payloadcms/db-postgres: 3.90.2
next: 16.3.3
Node: 22.23.3
pnpm: 11.27.1
OS: Linux x64
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions