How to Get File Size in onUpload with Convex R2 When getMetadata Returns Null?
Hi everyone,
I'm working with Convex and the R2 component for file uploads. My goal is to get the size of the uploaded file immediately after the upload completes, specifically within the onUpload callback, so I can track storage usage per user.
The issue I'm encountering is that when I call r2.getMetadata(ctx, key) inside the onUpload function, it returns null. I suspect this is because onUpload might be running as part of the syncMetadata process, and the metadata isn't fully available or settled at that exact moment through r2.getMetadata.
Here's the relevant part of my r2.clientApi configuration:
How can I reliably get the file size (and other metadata) for a newly uploaded file within the Convex backend flow, ideally associated with the onUpload event or shortly thereafter?
Any insights, examples, or alternative approaches would be greatly appreciated!
Thanks!
15 Replies
Thanks for posting in <#1088161997662724167>.
Reminder: If you have a Convex Pro account, use the Convex Dashboard to file support tickets.
- Provide context: What are you trying to achieve, what is the end-user interaction, what are you seeing? (full error message, command output, etc.)
- Use search.convex.dev to search Docs, Stack, and Discord all at once.
- Additionally, you can post your questions in the Convex Community's <#1228095053885476985> channel to receive a response from AI.
- Avoid tagging staff unless specifically instructed.
Thank you!
Makes sense,
onUpload()
runs before the actual upload, so you can throw an error to stop it if you choose. An afterUpload()
hook is what you're looking foryes, but there is no
afterUpload()
hook available is there any workaround?🥲I can put out a quick update that adds size to the
onUpload
args
It would be straight from the file object before upload. Would that work?
Or do you need more infothat'll be great👍 I think size is all I need
to confirm, you're using
useUploadFile
right
Because onUpload
is technically onSyncMetadata
yes
has to be afterUpload, anything else is just trusting file info passed in from the client
should still be doable tonight
makes sense, never trust client. Look forward to seeing it🫡
cool, will check it out once have time!
It seems that I can't get auth info from the context
Logs:
@erquhart am I missing something?
I am using clerk btw, and I can get identify from ctx in other functions
Ah yeah, that runs in a scheduled function. Have to think about how to get auth to it
I see, so it is expected behavior.
Yeah, but it needs to be documented at least. Best bet is to use onUpload to persist whatever part of the operation you’re trying to do that makes sense - you have the key and an authenticated user there, just no metadata yet.
Then after metadata sync, look up by key to get the user associated with the file.
good point, I'll try it
It works like a charm!
Thank you so much