Skip to content

cropping image on create fails with "Failed to persist upload data" #15991

Open

Description

@zubricks

Describe the Bug

Uploading an image and applying a crop during initial document creation fails to save the S3 URL/metadata back to the document. The server logs a warning: Failed to persist upload data for collection <slug> document <id>. The file itself is uploaded to S3 successfully — only the metadata persistence step fails.

This does not happen when uploading without a crop, or when cropping an already-saved document.

Regression likely introduced in PR #15570

Link to the code that reproduces this issue

packages/plugin-cloud-storage/src/hooks/afterChange.ts

Reproduction Steps

  1. Set up an upload collection with @payloadcms/storage-s3 and crop/image sizes configured
  2. In the Admin UI, create a new document in that collection
  3. Upload an image and use the crop tool before saving
  4. Save the document
  5. Check server logs — Failed to persist upload data warning appears and the document's url field is not populated

Which area(s) are affected?

plugin: storage-*

Environment Info

Binaries:
  Node: 23.11.0
  npm: 11.4.2
  Yarn: N/A
  pnpm: 10.10.0
Relevant Packages:
  payload: 3.79.0
  next: 15.4.11
  @payloadcms/db-postgres: 3.79.0
  @payloadcms/drizzle: 3.79.0
  @payloadcms/graphql: 3.79.0
  @payloadcms/next/utilities: 3.79.0
  @payloadcms/richtext-lexical: 3.79.0
  @payloadcms/translations: 3.79.0
  @payloadcms/ui/shared: 3.79.0
  react: 19.2.1
  react-dom: 19.2.1

Activity

  1. added
    status: needs-triage
    validate-reproduction
    on Mar 18, 2026
  2. added and removed
    validate-reproduction
    on Mar 18, 2026
  3. github-actions commented on Mar 18, 2026

    @github-actions
    Contributor

    Please add a reproduction in order for us to be able to investigate.

    Depending on the quality of reproduction steps, this issue may be closed if no reproduction is provided.

    Why was this issue marked with the invalid-reproduction label?

    To be able to investigate, we need access to a reproduction to identify what triggered the issue. We prefer a link to a public GitHub repository created with create-payload-app@latest -t blank or a forked/branched version of this repository with tests added (more info in the reproduction-guide).

    To make sure the issue is resolved as quickly as possible, please make sure that the reproduction is as minimal as possible. This means that you should remove unnecessary code, files, and dependencies that do not contribute to the issue. Ensure your reproduction does not depend on secrets, 3rd party registries, private dependencies, or any other data that cannot be made public. Avoid a reproduction including a whole monorepo (unless relevant to the issue). The easier it is to reproduce the issue, the quicker we can help.

    Please test your reproduction against the latest version of Payload to make sure your issue has not already been fixed.

    I added a link, why was it still marked?

    Ensure the link is pointing to a codebase that is accessible (e.g. not a private repository). "example.com", "n/a", "will add later", etc. are not acceptable links -- we need to see a public codebase. See the above section for accepted links.

    Useful Resources

  4. removed theissue type on Mar 18, 2026
  5. added theissue type on Mar 18, 2026
  6. maiklukasch commented on Apr 24, 2026

    @maiklukasch

    I have the same bug. Cropping when creating an image and image record doesnt get stored into the images-table

  7. sam9191 commented on Jul 18, 2026

    @sam9191

    I hit a different symptom of what I believe is the same root cause, and traced it through the source. The bug is that the cloud-storage plugin's internal metadata update re-enters Payload's file re-processing path because req.query.uploadEdits is never cleared.

    Root cause

    After an upload, plugin-cloud-storage's afterChange hook persists upload metadata via an internal req.payload.update() that reuses the same req:

    https://github.com/payloadcms/payload/blob/main/packages/plugin-cloud-storage/src/hooks/afterChange.ts

    Before that call it sets req.context.skipCloudStorage = true and clears req.file and req.payloadUploadSizes ("Clear to prevent re-processing") — but it does not clear req.query.uploadEdits.

    Meanwhile, core's generateFileData reads uploadEdits straight from req.query on every update (parseUploadEditsFromReqOrIncomingData in packages/payload/src/uploads/generateFileData.ts), and shouldReupload() returns true whenever it contains a crop/resize/focal change. So the plugin's supposedly data-only metadata update re-enters the full file-regeneration path: with req.file cleared, generateFileData tries to re-fetch the file (getExternalFile / getFileByPath) and re-run sharp with the crop applied a second time.

    Symptoms

    • This issue (create + crop): the re-fetch on the internal update pass fails (e.g. the doc's url isn't fetchable from the server at that moment), the error is caught in afterChange, and you get Failed to persist upload data... with the URL/metadata never written.
    • My case (update + crop, custom beforeOperation hook that populates req.file): the internal update pass re-runs sharp, getSafeFileName() bumps the filename another generation, but since skipCloudStorage makes the plugin skip its uploads, the DB filename ends up one generation ahead of the objects actually stored in S3 — and the next image edit 404s.

    Both fall out of the same thing: the stale uploadEdits in req.query makes the metadata-persistence update look like a fresh image edit.

    Suggested fix

    In afterChange.ts, alongside clearing req.file and req.payloadUploadSizes, also strip uploadEdits from req.query (or pass a req without the query) before the internal update(). Alternatively, core could ignore req.query.uploadEdits when req.context.skipCloudStorage is set, but sanitizing the req in the plugin seems cleaner since it owns the internal update.

    Workaround

    A beforeOperation hook on the upload collection that strips the stale edits on the plugin's internal pass:

    const stripStaleUploadEdits: CollectionBeforeOperationHook = ({ args, operation, req }) => {
      if (operation === 'update' && req.context?.skipCloudStorage) {
        if (req.query && 'uploadEdits' in req.query) {
          delete (req.query as Record<string, unknown>).uploadEdits
        }
      }
      return args
    }

    Reproduced on 3.80.0; the relevant code is unchanged on current main.

  8. umkasanki commented on Aug 6, 2026

    @umkasanki

    We are hitting what looks like exactly this bug, and can offer a full reproduction plus the mechanism, since the issue is waiting on one. Two updates from current versions:

    • On payload / plugin-cloud-storage 3.85.2 the symptom has escalated: the afterChange hook's catch block now rethrows, so instead of the logged "Failed to persist upload data" warning the whole save fails with HTTP 400 — "There was a problem while uploading the file". Any upload saved with a crop fails on a cloud-storage install (admin UI or REST); focal-point-only edits survive.
    • Verified against packages/plugin-cloud-storage/src/hooks/afterChange.ts on current main: the cleanup gap described below is still there.

    Environment

    Package Version
    payload 3.85.2
    @payloadcms/plugin-cloud-storage 3.85.2
    @payloadcms/storage-s3 3.85.2
    @payloadcms/db-postgres 3.85.2
    next 16.2.12
    sharp 0.34.2
    Node 22.23.2

    Reproduction

    1. An upload collection with crop: true (default) and some imageSizes, storage via @payloadcms/storage-s3.
    2. In the admin UI: upload an image, open the crop tool, apply any crop, save. Equivalently via REST — multipart file body plus:
    POST /api/images?uploadEdits[crop][unit]=%25&uploadEdits[crop][x]=0&uploadEdits[crop][y]=10.47&uploadEdits[crop][width]=91.89&uploadEdits[crop][height]=42.9&uploadEdits[focalPoint][x]=24&uploadEdits[focalPoint][y]=31&uploadEdits[heightInPixels]=644&uploadEdits[widthInPixels]=1103
    
      1. The same request without the crop params succeeds.

    Error output

    BadRequestError: There was a problem while uploading the file.
    Caused by: Error: extract_area: bad extract area
        at cropImage (payload/dist/uploads/cropImage.js:49)
        at generateFileData (payload/dist/uploads/generateFileData.js:201)
        at updateByIDOperation (...)          ← the plugin's nested metadata update
        at getAfterChangeHook (@payloadcms/plugin-cloud-storage/dist/hooks/afterChange.js)
        at createOperation (...)              ← the original request
    

    Mechanism

    1. The original create/update carries req.query.uploadEdits with a crop. generateFileData crops the file correctly — the first pass is fine.
    2. plugin-cloud-storage's afterChange hook uploads the files to the adapter and then persists the adapter's upload metadata via a nested req.payload.update({ id, data: uploadMetadata, req }) reusing the same req. Before that call it sets req.context.skipCloudStorage = true and clears req.file and req.payloadUploadSizes ("Clear to prevent re-processing") — but it does not clear req.query.uploadEdits.
    3. The nested update re-enters generateFileData: parseUploadEditsFromReqOrIncomingData picks up the leaked req.query.uploadEdits, shouldReupload returns true because uploadEdits.crop is set, and cropImage applies the original pixel rectangle (widthInPixels/heightInPixels describe the original file) to the already-cropped file → extract_area: bad extract area.
    4. The rethrow in the hook's catch turns that into a 400 for the whole save.

    This matches @sam9191's earlier analysis in this thread; focal-only edits pass because the parser bails when the incoming focal point equals the stored one — which is why the bug only bites when a crop is involved.

    Suggested fix

    In getAfterChangeHook, alongside the existing req.file = undefined / req.payloadUploadSizes = undefined, drop the already-consumed edits before the nested update:

    delete (req.query as Record<string, unknown> | undefined)?.uploadEdits

    Or, more defensively, have parseUploadEditsFromReqOrIncomingData ignore query uploadEdits when there is no req.file to process.

    Userland workaround

    A beforeOperation hook on the upload collection, keyed off the plugin's own marker for its internal update:

    import type { CollectionBeforeOperationHook } from 'payload'
    
    export const stripLeakedUploadEdits: CollectionBeforeOperationHook = ({ args, operation, req }) => {
      if (operation === 'update' && req.context?.skipCloudStorage && req.query?.uploadEdits) {
        delete req.query.uploadEdits
      }
      return args
    }

    By the time skipCloudStorage is set the original request has fully consumed the edits, so deleting them there is safe. With this hook in place, create-with-crop returns 201 with a correctly single-cropped file on our install.

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

    Bugcreated-by: Payload teamplugin: storage-*status: needs-triage

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions