Repository navigation
refactor!: centralize client upload instructions in Payload core - #17312
Conversation
📦 esbuild Bundle Analysis for payloadThis analysis was generated by esbuild-bundle-analyzer. 🤖
Largest pathsThese visualization shows top 20 largest paths in the bundle.Meta file: packages/next/meta_index.json, Out file: esbuild/index.js
Meta file: packages/payload/meta_index.json, Out file: esbuild/index.js
Meta file: packages/payload/meta_shared.json, Out file: esbuild/exports/shared.js
Meta file: packages/richtext-lexical/meta_client.json, Out file: esbuild/exports/client_optimized/index.js
Meta file: packages/ui/meta_client.json, Out file: esbuild/exports/client_optimized/index.js
Meta file: packages/ui/meta_shared.json, Out file: esbuild/exports/shared_optimized/index.js
DetailsNext to the size is how much the size has increased or decreased compared with the base branch of this PR.
|
| } | ||
|
|
||
| // 3. Create document in Payload (file already in storage) | ||
| const docResponse = await fetch(`/api/${collectionSlug}`, { |
There was a problem hiding this comment.
This old example was actually incorrect. Without sending clientUploadContext payload would not be able to match the document creation with the file previously uploaded
|
|
||
| type ClientUploadConfig = { | ||
| /** Whether this collection provides separate upload instructions. */ | ||
| uploadInstructions?: true |
There was a problem hiding this comment.
This is what the admin panel reads to know whether it should just upload the file normally through payload, or fetch upload instructions to upload the file directly to the storage provider
| ({ upload }) => typeof upload === 'object' && upload.uploadInstructions, | ||
| ) | ||
| ) { | ||
| config.endpoints.push(uploadInstructionsEndpoint) |
There was a problem hiding this comment.
Previously, every single storage provider pushed their own endpoint for this. Now, we push one generic, standardized endpoint. The storage provider just sets upload.uploadInstructions
| * Context of the file when it was uploaded via client side. | ||
| */ | ||
| clientUploadContext?: unknown | ||
| directUpload?: unknown |
There was a problem hiding this comment.
Previously, you had to pass the following to POST /api/<collectionslug> after the direct upload is done:
"clientUploadContext": {
"prefix": "gallery"
}
Now:
uploadReference: { prefix: 'gallery' },
This is what tells Payload
- the file is not provided here, it was uploaded directly before
- this is where I can find the file (in this case,
prefix- varies by provider, hence unknown)
| } & ( | ||
| | { | ||
| data?: unknown | ||
| name: string |
There was a problem hiding this comment.
For azure (multipart upload), and vercel/uploadthing (upload through their client sdk).
|
|
||
| const bytesToMB = (bytes: number) => bytes / 1024 / 1024 | ||
|
|
||
| export const uploadInstructionsEndpoint: Endpoint = { |
There was a problem hiding this comment.
New generic endpoint to fetch upload instructions, such as which signed URL to upload to. Replaces the adapter-specific handlers in:
storage-s3/src/generateSignedURL.ts
storage-azure/src/generateSignedURL.ts
storage-gcs/src/generateSignedURL.ts
storage-vercel-blob/src/getClientUploadRoute.ts
|
|
||
| const { access, generate } = uploadInstructions | ||
| if ( | ||
| access ? !(await access({ collectionSlug: uploadRequest.collectionSlug, req })) : !req.user |
There was a problem hiding this comment.
This is not new. Previously, the adapter-specific handlers just called the access control directly, since they owned it.
Now that payload owns it: the adapters pass the access control to the new collection?.config?.upload.uploadInstructions?.access property, payload then reads it
| withMetadata?: WithMetadata | ||
| } | ||
|
|
||
| export type UploadInstructionsAccess = (args: { |
There was a problem hiding this comment.
This is not new. Previously, the adapter-specific handlers just called the access control directly, since they owned it.
Now that payload owns it: the adapters pass the access control to the new collection?.config?.upload.uploadInstructions?.access property, payload then reads it
|
|
||
| export type UploadInstructionsCapability = { | ||
| /** Controls access to generating upload instructions. */ | ||
| access?: UploadInstructionsAccess |
There was a problem hiding this comment.
Since this is payload-owned, adapters now provide these to payload, which reads them in the generic upload instruction handler.
Regarding upload instructions: generate signed url = generate upload instructions. Same thing, different teminology. "signed url" would not be accurate, since that's not what azure, vercel blob and uploadthing returns.
| serverURL: string | ||
| updateFilename: (value: string) => void | ||
| }) => Promise<unknown> | ||
| name: string |
There was a problem hiding this comment.
If upload instructions are of type dispatch and not http, the name they return is matched to the listener created through here.
| tempFilePath?: string | ||
| } | ||
|
|
||
| export type ClientUploadsAccess = (args: { |
There was a problem hiding this comment.
Moved into payload package
| import { createClientUploadHandler } from '@payloadcms/plugin-cloud-storage/client' | ||
| import { formatAdminURL } from 'payload/shared' | ||
|
|
||
| export const AzureClientUploadHandler = createClientUploadHandler({ |
There was a problem hiding this comment.
Removed because Azure now uses the shared upload flow. Generic client handling moved to our shared packages/ui/src/providers/UploadHandlers/index.tsx, while Azure-specific upload instructions remain in packages/storage-azure/src/generateUploadInstructions.ts.
| useCompositePrefixes?: boolean | ||
| } | ||
|
|
||
| export const generateUploadInstructions = ({ |
There was a problem hiding this comment.
Renamed from generateSignedURL
| body: await createFormData( | ||
| form.formState, | ||
| overrides, | ||
| collectionSlug, |
There was a problem hiding this comment.
Removed - can be inferred from URL, so this was unnecessary
| const instructions = (await response.json()) as UploadInstructions | ||
| let uploadedFile = instructions.file | ||
|
|
||
| if (instructions.type === 'http') { |
There was a problem hiding this comment.
Shared generic handler for http upload instructions. Previously, each storage adapter needed to provide their own handler client component that does this
| } | ||
|
|
||
| const result = await new Promise<unknown>((resolve, reject) => { | ||
| const event = new CustomEvent(`payload:upload:${instructions.name}`, { |
There was a problem hiding this comment.
Here, type = dispatch.
=> same behavior as before: call client handler provided by the storage adapter.
Only difference: instead of getting the handler through uploadHandlers.get(, we broadcast an event that the storage adapter listens to.
We need to declare this as a generic dispatch instruction, because this is no longer just consumed by the admin panel. In MCP, we will treat dispatch instructions as "call external mcp tool"
…f and more accurate (e.g. R2 is not direct)
|
Confirmed critical bug: packages/payload/src/uploads/endpoints/uploadInstructions.ts:30 — |
# Conflicts: # docs/migration-guide/v4.mdx # docs/upload/storage-adapters.mdx # packages/storage-uploadthing/README.md # packages/storage-uploadthing/src/adapter.ts # packages/storage-uploadthing/src/client/UploadthingClientUploadHandler.ts # packages/storage-uploadthing/src/getClientUploadRoute.ts # packages/storage-uploadthing/src/getFile.ts # packages/storage-uploadthing/src/index.ts # packages/storage-uploadthing/src/uploadFile.ts
| type: 'dispatch', | ||
| data: { | ||
| pathname: resolved.fileKey, | ||
| token: await generateClientTokenFromReadWriteToken({ |
There was a problem hiding this comment.
The deleted getClientUploadRoute.ts wrapped the equivalent token-generation call in try/catch and logged unexpected errors via req.payload.logger.error(error) before rethrowing. This inline generate() has no surrounding try/catch, so a generateClientTokenFromReadWriteToken failure (bad credentials, Vercel API outage) now only surfaces to the client with no corresponding server-side log entry.
There was a problem hiding this comment.
We already have routeError.ts which catches all errors and logs them
|
|
||
| If you only configure a storage adapter with `clientUploads: true`, no migration is needed. The Admin Panel uses the new endpoint automatically. | ||
|
|
||
| `upload.limits.fileSize` is now checked before Payload returns upload instructions. This is new for Azure, GCS, R2, and Vercel Blob; S3 already enforced this limit. If these client uploads previously exceeded the server limit, increase `upload.limits.fileSize` or Payload will reject them before the upload begins. |
There was a problem hiding this comment.
The fileSize check looks to only exist in the s3 adapter, not the others. This is something that we should be doing, though. We should either update this to reflect current state or leave it and file an issue/task to update the other adapters with this check.
There was a problem hiding this comment.
This is already are up-to-date! Previous state: only S3 enforced this limit. Now: all adapters enforce this limit through shared endpoint.
This is new for Azure, GCS, R2, and Vercel Blob; S3 already enforced this limit.
Previously, each storage adapter had its own upload endpoint and Admin handler. This worked for the Admin Panel, but other tools had no standard way to upload files.
This PR adds one standardized endpoint that lives in Payload Core:
Payload checks the request and returns upload instructions. These instructions tell the caller where and how to upload the file, whether that uses a signed URL (e.g. S3) or a provider-specific uploader (e.g. uploadthing, vercel).
The Admin Panel uses these instructions now, and MCP can use them later without passing large files as base64. Files still upload directly to the storage provider where supported, and document creation does not change.
Example: S3 Admin Upload Flow
This example uploads
cat.jpgto themediacollection with the prefixgallery.Before This PR (main)
After This PR
The difference is only how the upload starts. Before, Admin used an S3 endpoint and S3 handler. Now, it asks Payload for upload instructions through one shared endpoint. The S3 upload and document request stay the same.
Other Storage Adapters
Some providers need their own SDK or multipart flow. They return a named
dispatchinstruction for the matching Admin helper:MCP
Standard instructions also make large MCP uploads possible (separate PR) without copying the file into a tool call as base64:
This PR only defines the shared contract. A follow-up will let MCP follow the instructions and then call
createDocumentorupdateDocument.Current Scope
For now, the endpoint is added only when a collection provides
uploadInstructions. Local storage and adapters without direct uploads will be supported next.Breaking Changes
Normal storage adapter configuration does not need to change, and the
clientUploadsoption is unchanged.Code that directly calls the old S3, Azure, or GCS signing endpoints must use
/api/upload-instructionsand follow the returnedrequest. The old adapter client component exports andsetUploadHandlerAPI are also removed. Custom client upload handlers must use a nameddispatchinstruction instead.Upload instructions now return a complete
filevalue for document creation. The oldclientUploadContextproperty, its redundanthandleUploadargument, and the duplicatecollectionSlugare removed. The presence ofuploadReferencetells Payload that the file is already in storage and gives the adapter any data it needs to find it.The
ClientUploadsAccesstype is removed from@payloadcms/plugin-cloud-storage/types. UseUploadInstructionsAccessfrompayloadinstead. The v4 migration guide includes detailed examples for each change.Next Steps
1. Support every upload collection
Payload will use direct provider instructions when available and Payload-managed temporary storage otherwise. The same endpoint will then work for every upload collection.
2. Add MCP upload support
The MCP plugin will follow the same instructions, then pass the completed upload to
createDocumentorupdateDocumentinstead of sending inline base64.