Unable to upload image to storage using Vercel's serverless (not using NextJS)
Bug report
Describe the bug
Since using vercel's serverless functions, I'm not able to upload images to storage. Used to work when only having a frontend but I had to use an API to hide my supabase credentials. I'm using 11ty and Alpine. Strangely, even though no image is uploaded, there are no error messages.
To Reproduce
Steps to reproduce the behavior, please provide code snippets or a repository:
Tried with fs and without fs: same problem.
import { createClient } from '@supabase/supabase-js'
import multiparty from 'multiparty'
import fs from 'fs'
export default async function handler(request, response) {
const form = new multiparty.Form()
const data = await new Promise((resolve, reject) => {
form.parse(request, function (err, fields, files) {
if (err) reject({ err })
resolve({ fields, files })
})
})
// console.log(`data: `, JSON.stringify(data))
const supabase = createClient(
process.env.SUPABASE_URL,
process.env.SUPABASE_KEY
)
try {
const imageFile = data.files.picture[0]
const imagePath = `public/${imageFile.originalFilename}`
supabase.storage
.from('test_images')
.upload(imagePath, fs.readFileSync(imageFile.path), {
contentType: imageFile.contentType,
})
.then(async (response) => {
await supabase.from('testimonials').insert({
description: data.fields.description[0],
name: data.fields.identity[0].split('/')[0].trim(),
occupation: data.fields.identity[0].split('/')[1].trim(),
picture:
'https://qroiybphgipjhkmfsvnj.supabase.co/storage/v1/object/public/' +
response.data.Key,
})
})
response.status(200).json({ message: 'Testimonial added succesfully.' })
} catch (error) {
response.status(500).json({ message: error })
}
}
Expected behavior
An upload of an image in storage which is then linked to a testimonial.
Screenshots
If applicable, add screenshots to help explain your problem.
System information
- OS: macOS
- Browser: Chrome
- Version of supabase-js: "@supabase/supabase-js": "^1.35.3",
- Version of Node.js: v16.0.0
Additional context
Sample data:
data: {
"fields": {
"description": [
"It is a long established etc..."
],
"identity": [
"Ella Fitzgerald / Singer"
]
},
"files": {
"picture": [
{
"fieldName": "picture",
"originalFilename": "humble.jpeg",
"path": "/var/folders/h3/q50t1r917ddbn9xgzzr8z13w0000gq/T/5vrhgasyAb_V-kCHVFhJvZu4.jpeg",
"headers": {
"content-disposition": "form-data; name=\"picture\"; filename=\"humble.jpeg\"",
"content-type": "image/jpeg"
},
"size": 498889
}
]
}
}
Hey @nsursock! From a cursory glance at your code, you don't seem to be awaiting the promise returned by storage.from(...).upload(...). This means that Vercel can terminate the serverless function after you send a HTTP response without waiting for the storage upload to complete. Could you try awaiting the promise?
Closing for inactivity, feel free to reach out if needed further assistance