Repository navigation
fix: s3 plugin uploads files before validation - #14988
Conversation
📦 esbuild Bundle Analysis for payloadThis analysis was generated by esbuild-bundle-analyzer. 🤖 |
|
🚀 This is included in version v3.70.0 |
### 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.
|
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? |
### 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.
|
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? |
|
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. |
|
Hi PayloadCMS team, Thank you for addressing the orphaned file issue with this PR. I understand the rationale behind moving upload logic from Positive ChangesImproved 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 Identified1. Hook Timing Change Requires Explicit Document UpdatesMoving the upload logic from Previous behavior:
Current behavior:
This breaking change was not clearly documented. Custom upload handlers that previously mutated the 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 MemoryWhile not directly caused by this PR, the move to The Problem: Next.js Server Actions cannot serialize native
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
However, without configuring Next.js Server Actions body size limit, large file uploads fail: 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 DefeatedThe reliance on Next.js Server Actions for file uploads fundamentally breaks modern cloud-native upload patterns: What should happen with
What actually happens:
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 ImplicationsThe base64 serialization approach has significant performance implications: Memory usage:
Deployment constraints:
Scalability concerns:
5. Security ImplicationsIncreasing
6. Breaking Changes for Custom Upload HandlersThis change breaks existing implementations in two ways: Hook behavior change:
Client-side upload patterns broken:
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 SolutionsOption 1: Exclude File Data When Using clientUploadContextWhen // 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 ActionsImplement 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 BufferingImplement 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 FlagAllow 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 RequirementsRegardless of which solution is chosen, the following documentation is essential: Breaking Changes Documentation:
Best Practices Guide:
Migration Guide:
SummaryThis PR introduces two distinct categories of issues: Direct Changes (from this PR):
Exposed Architecture Issues (pre-existing but now critical):
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
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
I'm happy to provide additional details, test proposed solutions, or discuss alternative approaches. Thank you for considering this feedback. |
|
And a possibly related PR: #15078 |
|
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 For anyone whose custom hooks are affected by this timing change, please share details — we can provide guidance and examples to update hooks for @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. |
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 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. |
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: |
|
@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:
🚫 Out of PR scope:
Thanks for bearing with us here, we appreciate the feedback and it’s directly informing follow-up improvements. |
|
@leonardigabriele try changing This should be the only change needed. |
…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`
This has been resolved with PR: |
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? |
|
Hi @JessRynkar, 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? |
What
Fixes issue with
plugin-cloud-storagewhere invalid files are still passed to the storage adapter.Why
Files are uploaded to external storage via the
beforeChangehook, 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
beforeChangetoafterChangehook inplugin-cloud-storageThis change only affects users of
@payloadcms/storage-s3or@payloadcms/plugin-cloud-storagewho have custom hooks on upload fields.afterChange, ensuring the file has passed all validations and the document has been successfully saved before external storage.beforeChangewill need to be updated.