Skip to content

fix: s3 plugin uploads files before validation - #14988

Merged
JessRynkar merged 3 commits into
mainfrom
fix/s3-uploads
Jan 5, 2026
Merged

JessRynkar merged 3 commits into
mainfrom
fix/s3-uploads

Conversation

@JessRynkar

@JessRynkar JessRynkar commented Dec 19, 2025 •

Copy link
Copy Markdown
Member

What

Fixes issue with plugin-cloud-storage where invalid files are still passed to the storage adapter.

Why

Files are uploaded to external storage via the beforeChange hook, which runs before field-level validation.

Therefore, even if a file fails validation, it has already been uploaded to the external storage, resulting in orphaned files.

How

  • Moved upload logic from beforeChange to afterChange hook in plugin-cloud-storage
  • Added int tests to verify behavior

⚠️ Breaking Change

This change only affects users of @payloadcms/storage-s3 or @payloadcms/plugin-cloud-storage who have custom hooks on upload fields.

  • External uploads now occur in afterChange, ensuring the file has passed all validations and the document has been successfully saved before external storage.
  • Custom hooks that relied on the file being available in beforeChange will need to be updated.
  • Standard usage of the plugin is unaffected. Users who are not overriding hooks will see no change.

@github-actions

github-actions Bot commented Dec 19, 2025 •

Copy link
Copy Markdown
Contributor

📦 esbuild Bundle Analysis for payload

This analysis was generated by esbuild-bundle-analyzer. 🤖
This PR introduced no changes to the esbuild bundle! 🙌

@JessRynkar
JessRynkar merged commit 502947b into main Jan 5, 2026
@JessRynkar
JessRynkar deleted the fix/s3-uploads branch January 5, 2026 16:29
@github-actions

github-actions Bot commented Jan 5, 2026

Copy link
Copy Markdown
Contributor

🚀 This is included in version v3.70.0

zubricks pushed a commit that referenced this pull request Jan 6, 2026
### What
Fixes issue with `plugin-cloud-storage` where invalid files are still
passed to the storage adapter.

### Why
Files are uploaded to external storage via the `beforeChange` hook,
which runs before field-level validation.

Therefore, even if a file fails validation, it has already been uploaded
to the external storage, resulting in orphaned files.

### How
- Moved upload logic from `beforeChange` to `afterChange` hook in
`plugin-cloud-storage`
- Added int tests to verify behavior

# Important
This change moves the external file uploading process from
`beforeChange` to the `afterChange` hook in the S3 plugin. It may break
custom code that overrides the `beforeChange` hook and expects files to
be uploaded earlier. Standard usage without overrides is unaffected.
@leonardigabriele

Copy link
Copy Markdown

Hi, I had some code executing in an afterChange hook which now breaks uploads. Is it possible to compose other hooks with the upload functionality?
Thanks

teastudiopl pushed a commit to teastudiopl/payload that referenced this pull request Jan 8, 2026
### What
Fixes issue with `plugin-cloud-storage` where invalid files are still
passed to the storage adapter.

### Why
Files are uploaded to external storage via the `beforeChange` hook,
which runs before field-level validation.

Therefore, even if a file fails validation, it has already been uploaded
to the external storage, resulting in orphaned files.

### How
- Moved upload logic from `beforeChange` to `afterChange` hook in
`plugin-cloud-storage`
- Added int tests to verify behavior

# Important
This change moves the external file uploading process from
`beforeChange` to the `afterChange` hook in the S3 plugin. It may break
custom code that overrides the `beforeChange` hook and expects files to
be uploaded earlier. Standard usage without overrides is unaffected.
@JessRynkar

Copy link
Copy Markdown
Member Author

Hi @leonardigabriele, when you say “compose other hooks with the upload functionality,” what do you mean by this?

Could you share what your hook is trying to achieve so we can see the best way to make it work with this change?

@robinscholz

Copy link
Copy Markdown
Contributor

This is a breaking change and should be kept configurable. It completely breaks a custom media plugin for client side uploads we have developed. Please make the hook configurable, so we can keep the old implementation.

@ChristophJeworutzki

ChristophJeworutzki commented Jan 11, 2026 •

Copy link
Copy Markdown

Hi PayloadCMS team,

Thank you for addressing the orphaned file issue with this PR. I understand the rationale behind moving upload logic from beforeChange to afterChange to prevent invalid uploads from reaching external storage. However, I've encountered significant issues after upgrading to v3.70.0 that I believe warrant discussion and potentially require architectural reconsideration.

Positive Changes

Improved Data Integrity

Validating files before upload eliminates orphaned uploads in external storage (S3, R2, etc.), which improves data consistency and reduces storage costs. This is a meaningful improvement to the upload workflow.

Clearer Separation of Concerns

The separation between validation and upload logic is architecturally sound in principle and makes the hook responsibilities more explicit.

Critical Issues Identified

1. Hook Timing Change Requires Explicit Document Updates

Moving the upload logic from beforeChange to afterChange means:

Previous behavior:

  • Upload occurred before document was saved to database
  • Modifications to data parameter were automatically persisted
  • Single database write operation

Current behavior:

  • Document is saved to database first (without upload data)
  • Upload occurs after database save
  • Upload handler must explicitly call req.payload.update() to persist changes
  • Requires two database write operations

This breaking change was not clearly documented. Custom upload handlers that previously mutated the data parameter now silently fail to persist mimeType, storage, and other upload-related fields unless explicitly updated.

Example fix required:

// Custom upload handler now needs explicit update
afterChange: async ({ doc, req }) => {
  const uploadResult = await uploadToS3(doc.file)
  
  // This is now required - data doesn't automatically persist
  await req.payload.update({
    collection: 'media',
    id: doc.id,
    data: {
      mimeType: uploadResult.mimeType,
      storage: 's3',
      url: uploadResult.url,
    }
  })
}

2. Next.js Server Actions Force Files Through Server Memory

While not directly caused by this PR, the move to afterChange has highlighted a fundamental architectural problem with how PayloadCMS handles file uploads in Next.js App Router.

The Problem:

Next.js Server Actions cannot serialize native File objects. PayloadCMS works around this by converting files to base64 strings for transmission:

  1. Client-side: File → base64 string (~33% size increase)
  2. Server Action: Receives base64 string
  3. Server: base64ToFile() → File object
  4. Upload handler: Processes File object

This occurs even when using client-side upload patterns (TUS, direct-to-S3, Mux, etc.) where the file upload should bypass the server entirely.

Concrete Evidence:

I've implemented a plugin using @payloadcms/plugin-cloud-storage that performs client-side uploads:

  • Files upload directly to TUS/Mux endpoints from the browser
  • Only upload metadata (clientUploadContext) should reach the server
  • File content should never touch the application server

However, without configuring Next.js Server Actions body size limit, large file uploads fail:

[Error: Body exceeded 1 MB limit.
To configure the body size limit for Server Actions, see: https://nextjs.org/docs/app/api-reference/next-config-js/serverActions#bodysizelimit] {
  statusCode: 413,
  digest: '1256826503'
}

This proves that PayloadCMS sends the entire file through Server Actions even when using client-side uploads.

Required workaround:

// next.config.mjs
import { withPayload } from '@payloadcms/next/withPayload'

/** @type {import('next').NextConfig} */
const nextConfig = {
  experimental: {
    serverActions: {
      bodySizeLimit: '100mb', // Required: file content sent through Server Actions despite client-side upload
    },
  },
}

export default withPayload(nextConfig)

A 25MB video file becomes approximately 33MB as base64 in the Server Action payload, requiring this configuration despite the file being uploaded client-side to external storage.

3. Client-Side Upload Strategy Completely Defeated

The reliance on Next.js Server Actions for file uploads fundamentally breaks modern cloud-native upload patterns:

What should happen with clientUploadContext:

  • Client uploads file directly to TUS endpoint, S3, Mux, etc.
  • Client sends only metadata to server: { storage: 'mux', uploadId: 'abc123', mimeType: 'video/mp4' }
  • Server receives ~100 bytes of JSON
  • File content never touches application server

What actually happens:

  • Client uploads file to external storage ✓
  • Client ALSO base64-encodes entire file and sends through Server Action ✗
  • Server receives ~33MB for a 25MB video
  • Server deserializes file (even though it's not used)
  • Handler only uses the metadata

This defeats the entire purpose of client-side uploads. The file is forced through server memory despite the upload already being completed externally.

4. Performance and Memory Implications

The base64 serialization approach has significant performance implications:

Memory usage:

  • Server memory consumption increases dramatically for large file uploads
  • Multiple concurrent uploads can quickly exhaust available memory
  • Base64 encoding/decoding adds computational overhead
  • Memory is wasted processing files that have already been uploaded elsewhere

Deployment constraints:

  • Edge/Serverless platforms (Vercel, Netlify, AWS Lambda) typically have memory limits around 1GB
  • Serverless functions have execution timeouts of 10-30 seconds
  • Large file uploads may exceed these platform limitations
  • Makes PayloadCMS unsuitable for serverless deployments with file upload requirements

Scalability concerns:

  • Creates memory spikes during upload processing
  • Requires vertical scaling (more RAM) rather than horizontal scaling
  • Concurrent uploads compound the memory pressure
  • Redundant processing of already-uploaded files

5. Security Implications

Increasing bodySizeLimit values expands the attack surface:

  • Malicious users can exhaust server memory with large payloads
  • Distributed Denial of Service (DoS) attacks become simpler to execute
  • Higher payload limits increase the potential impact of each malicious request
  • No built-in rate limiting or memory protection for file uploads
  • Attack surface exists even when files are uploaded client-side

6. Breaking Changes for Custom Upload Handlers

This change breaks existing implementations in two ways:

Hook behavior change:

  • Custom handlers that relied on mutating data in beforeChange no longer work
  • Must now explicitly call req.payload.update() in afterChange

Client-side upload patterns broken:

  • TUS resumable uploads
  • Direct-to-S3/Cloudflare R2 uploads
  • Mux direct uploads
  • Any pattern that bypasses server processing

Even when implementing client-side uploads correctly, files are still forced through server memory via Next.js Server Actions. This represents a significant architectural regression for applications following cloud-native upload best practices.

Proposed Solutions

Option 1: Exclude File Data When Using clientUploadContext

When clientUploadContext is provided, do not send file data through Server Actions:

// Client-side: Detect client upload and exclude file
if (clientUploadContext) {
  // Only send metadata, not file content
  await serverAction({ 
    clientUploadContext,
    // file is NOT included
  })
} else {
  // Traditional upload: send file
  await serverAction({ 
    file: await fileToBase64(file),
  })
}

This would allow true client-side uploads without forcing files through server memory.

Option 2: Support Native File Handling Outside Server Actions

Implement upload endpoints that don't rely on Next.js Server Actions:

// Use traditional Next.js Route Handlers for file uploads
// app/api/upload/route.ts
export async function POST(request: Request) {
  const formData = await request.formData()
  const file = formData.get('file') as File // Native File object, no base64
  
  // Process with custom handler
  return customUploadHandler(file)
}

This avoids the Server Actions serialization issue entirely while maintaining support for custom upload handlers.

Option 3: Pre-Validation Without Full Buffering

Implement a validation phase that doesn't require loading entire file contents:

upload: {
  preValidate: async (fileMetadata) => {
    // Validate mimetype, size, filename, etc. without loading file content
    if (!allowedMimeTypes.includes(fileMetadata.mimetype)) {
      throw new Error('Invalid file type')
    }
    if (fileMetadata.size > maxFileSize) {
      throw new Error('File too large')
    }
    return { valid: true }
  },
  handler: async (file) => {
    // Only called after pre-validation passes
    // Can implement client-side upload strategies here
  }
}

This approach allows lightweight validation based on file metadata without requiring the entire file to be buffered in memory.

Option 4: Client-Side Upload Configuration Flag

Allow fields to specify that uploads should happen entirely client-side:

upload: {
  clientSideUpload: true, // Explicitly skip sending file through Server Actions
  handler: myCustomHandler, // Receives upload metadata only via clientUploadContext
  getUploadUrl: async () => {
    // Return presigned URL or TUS endpoint
    return { url: 'https://tus.example.com/upload' }
  }
}

Server only receives upload result metadata after client-side upload completes.

Documentation Requirements

Regardless of which solution is chosen, the following documentation is essential:

Breaking Changes Documentation:

  • Hook timing change from beforeChange to afterChange
  • Requirement to explicitly call req.payload.update() in custom handlers
  • bodySizeLimit configuration requirements and implications
  • Memory and infrastructure scaling considerations
  • Migration path for existing implementations
  • Impact on client-side upload implementations

Best Practices Guide:

  • Recommended bodySizeLimit values for different use cases
  • Edge/serverless deployment limitations and workarounds
  • Alternative strategies for very large files
  • Security considerations for increased payload limits
  • How client-side uploads currently work (and their limitations)

Migration Guide:

  • Step-by-step instructions for updating custom upload implementations
  • Code examples showing before/after patterns for beforeChange to afterChange
  • Troubleshooting common issues (fields not persisting, memory errors, body size limits)

Summary

This PR introduces two distinct categories of issues:

Direct Changes (from this PR):

  • Hook timing change requires explicit document updates in custom handlers
  • Breaking change for existing implementations not clearly documented
  • Two database writes instead of one (potential performance impact)

Exposed Architecture Issues (pre-existing but now critical):

  • Next.js Server Actions force base64 file serialization
  • Files are sent through Server Actions even when using clientUploadContext for client-side uploads
  • Entire file content must pass through server memory despite external upload completion
  • Client-side upload strategies are effectively broken
  • Serverless/edge deployments face severe limitations
  • Security implications of large payload limits

While the goal of preventing orphaned uploads is valuable, the current implementation has significant architectural drawbacks. The validation improvement should not come at the cost of forcing all file data through server memory, especially when those files have already been uploaded directly to external storage via client-side mechanisms.

The critical issue: PayloadCMS sends the entire file through Server Actions even when using clientUploadContext for client-side uploads. This means:

  • A file uploaded directly to Mux/TUS is also sent through your Next.js server
  • Server memory is consumed processing files that don't need server processing
  • bodySizeLimit configuration is required even for true client-side uploads
  • The purpose of client-side uploads is completely defeated

The underlying issue is PayloadCMS's reliance on Next.js Server Actions for file uploads. Server Actions were not designed for large file transfers and force an inefficient base64 serialization pattern. Alternative approaches (Route Handlers, streaming, excluding files when using clientUploadContext) should be considered.

I strongly encourage reconsideration of the file upload architecture. The proposed solutions above would maintain the validation benefits while restoring the ability to implement efficient, scalable file upload strategies.

Environment Details

  • PayloadCMS: 3.70.0
  • Next.js: 15.4.10
  • Node.js: 20.x
  • Deployment: Various environments (local development, Vercel, self-hosted)

I'm happy to provide additional details, test proposed solutions, or discuss alternative approaches. Thank you for considering this feedback.

@robinscholz

robinscholz commented Jan 12, 2026 •

Copy link
Copy Markdown
Contributor

Related issues:

#15073
#12671

@robinscholz

Copy link
Copy Markdown
Contributor

And a possibly related PR: #15078

@JessRynkar

JessRynkar commented Jan 12, 2026 •

Copy link
Copy Markdown
Member Author

Hi everyone, we carefully reviewed the feedback here. Initially we didn’t consider this as a breaking change because it only affects users with custom hooks on S3 upload fields (as mentioned in the PR description under impact). Standard usage is unaffected, but seeing community feedback, we will now escalate it to a breaking change in the release notes and PR to make this explicit.

We cannot revert the external upload process to beforeChange because that behavior was never correct: files could reach external storage before validation, leading to orphaned files and potential failures in custom hooks. afterChange is the only safe point where we can guarantee the file has passed all validations and the document has been successfully saved. This ensures correctness, prevents orphaned files, and maintains consistency with Payload’s validation and hook logic.

For anyone whose custom hooks are affected by this timing change, please share details — we can provide guidance and examples to update hooks for afterChange.

@ChristophJeworutzki, we appreciate the detailed feedback and the context you provided. To keep this PR focused, please open new issues for any additional concerns or issues that fall outside the scope of this PR or pre-date it, so we can track and address them separately.

@robinscholz

Copy link
Copy Markdown
Contributor

We cannot revert the external upload process to beforeChange because that behavior was never correct: files could reach external storage before validation, leading to orphaned files and potential failures in custom hooks. afterChange is the only safe point where we can guarantee the file has passed all validations and the document has been successfully saved. This ensures correctness, prevents orphaned files, and maintains consistency with Payload’s validation and hook logic.

As @ChristophJeworutzki points out in detail the underlying approach is flawed, which this PR surfaced. Client-side uploads should never touch the server, due to the various reasons lined out above.

Our plugin uses createClientUploadHandler to create a custom component which checks the mime type and then uploads the file to either S3 or Mux via client-side uploads. The component returns an object with filename, uploadId, mimeType, storage, which was automatically processed by payload inside the beforeChange hook.

This PR, by changing the hook, forces us to load huge video files into memory for no particular reason at all. It also breaks prior existing logic we relied on when designing the plugin.

I kindly ask you to take this very detailed feedback above into consideration and figure out how to best approach this. Otherwise Payload as a whole will be severely lacking for the foreseeable future in regards to media handling compared to comparable content management systems.

I’d suggest you start by opening up an issue yourself based on the findings by @ChristophJeworutzki. He has already spent a considerable amount of time surfacing and documenting these issues.

@leonardigabriele

leonardigabriele commented Jan 12, 2026 •

Copy link
Copy Markdown

Hi everyone, we carefully reviewed the feedback here. Initially we didn’t consider this as a breaking change because it only affects users with custom hooks on S3 upload fields (as mentioned in the PR description under impact). Standard usage is unaffected, but seeing community feedback, we will now escalate it to a breaking change in the release notes and PR to make this explicit.

We cannot revert the external upload process to beforeChange because that behavior was never correct: files could reach external storage before validation, leading to orphaned files and potential failures in custom hooks. afterChange is the only safe point where we can guarantee the file has passed all validations and the document has been successfully saved. This ensures correctness, prevents orphaned files, and maintains consistency with Payload’s validation and hook logic.

For anyone whose custom hooks are affected by this timing change, please share details — we can provide guidance and examples to update hooks for afterChange.

@ChristophJeworutzki, we appreciate the detailed feedback and the context you provided. To keep this PR focused, please open new issues for any additional concerns or issues that fall outside the scope of this PR or pre-date it, so we can track and address them separately.

Hi @JessRynkar , in my hook I am translating the document fields in other languages with an external service, for example the alternative text field for images. If I include the hook in the 3.70 version, the images do not get uploaded, specifically using local API payload.create. Here is my hook code:

export const translateHook: CollectionAfterChangeHook = async ({
  operation,
  data,
  doc,
  collection,
  context,
  req,
}) => {
  const locale = req.locale;
  const translate = context.translate as TranslateContext;

  if (!translate || operation !== "create") return;

  const itemsToTranslate = extractStrings(data, translate.fields, translate.blocks || {});

  for (const target of translate.locales) {
    if (target === locale) continue;

    let finalData = data;

    if (itemsToTranslate.length > 0) {
      const limit = pLimit(3);

      const translatedValues = await Promise.all(
        itemsToTranslate.map((item) => limit(() => translateService({ text: item.value, target })))
      );

      const translationsWithPaths = itemsToTranslate.map((item, index) => ({
        path: item.path,
        value: translatedValues[index],
        type: item.type,
      }));

      finalData = await applyTranslations(data, translationsWithPaths, req.payload.config);
    }

    await req.payload.update({
      collection: collection.slug,
      id: doc.id,
      data: finalData,
      locale: target,
      context: { llm: true },
      req,
    });
  }
};

@JessRynkar

JessRynkar commented Jan 13, 2026 •

Copy link
Copy Markdown
Member Author

@ChristophJeworutzki and @robinscholz there is a lot of info between what you both shared and we want to consider it properly, here is how we have broken it down:

✅ Fixes needed:

⚠️ Intentional / expected:

  • Moving uploads from beforeChange → afterChange is deliberate to prevent orphaned files and ensure validation. Any logic relying on pre-validation upload must move to afterChange.
  • Non-configurable option: reverting this change would reintroduce orphaned file issues, so we are keeping the new behavior as default and will continue to improve the functionality.

🚫 Out of PR scope:

Thanks for bearing with us here, we appreciate the feedback and it’s directly informing follow-up improvements.

@JessRynkar

Copy link
Copy Markdown
Member Author

@leonardigabriele try changing let finalData = data to let finalData = doc. The doc parameter contains the saved document with all upload metadata included, your hook uses the data parameter as the base for translations, but data doesn't include the cloud storage metadata (url, sizes, etc.).

This should be the only change needed.

JessRynkar added a commit that referenced this pull request Jan 13, 2026
…andleUpload (#15188)

### What
Fixes issue where storage metadata (object keys, timestamps, custom IDs,
etc.) from external providers (s3, azure, etc) is no longer persisted
back to the main doc. This issue was introduced in PR #14988 when the
external upload process was moved from the `beforeChange` to
`afterChange` hook.

### Why
Without automatically persisting metadata from external storage, users
have to manually update the doc themselves. This restores backward
compatibility for existing custom storage adapters.

### Where
Added automatic data capture/persistence in
`packages/plugin-cloud-storage/src/hooks/afterChange`

#### Testing
Added to test suite `test/plugin-cloud-storage`
@JessRynkar

Copy link
Copy Markdown
Member Author

✅ Fixes needed:

Custom handleUpload implementations no longer automatically persist returned metadata (url, id), requiring req.payload.update(). We will fix this internally and add a safe way for adapters to return results that get merged into the document post-validation.

This has been resolved with PR:

@leonardigabriele

leonardigabriele commented Jan 16, 2026 •

Copy link
Copy Markdown

@leonardigabriele try changing let finalData = data to let finalData = doc. The doc parameter contains the saved document with all upload metadata included, your hook uses the data parameter as the base for translations, but data doesn't include the cloud storage metadata (url, sizes, etc.).

This should be the only change needed.

Hi @JessRynkar , it does not work. As you can see I am updating the same doc at upload creation but in other languages. Even if I pass the straight doc to data without any transformation it breaks the upload. Can you suggest a workaround?

@jhb-dev

jhb-dev commented Jan 23, 2026 •

Copy link
Copy Markdown
Contributor

Hi @JessRynkar,
I am not entirely sure whether this PR is the cause, but since Payload 3.7x it no longer seems possible to rely on id inside a validate function to determine whether the media has already been uploaded.

Previously, this allowed us to make the alt text required only after the file existed in the external storage.

Example:

{
  name: 'alt',
  type: 'textarea',
  required: true,
  validate: (value, { id }) => {
    // If the document has an id, the media file was uploaded, so the alt text should be required
    if (id) {
      if (!value || value.trim().length === 0) {
        return 'The alt text is required'
      }
    }

    // Alt text is not required before upload (because automatic alt text generation depends on a the file being uploaded)
    return true
  },
}

Is this expected or an issue?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants