To allow users to update their avatars, you need to combine a client-side upload component with a server-side API route. The process involves:
- Client-side: Use an
ImageUpload component to handle file selection and upload the file to a Supabase Storage bucket using the uploadImage utility. - Storage: The file is uploaded to a specific bucket (e.g.,
"avatar") and organized into a folder named after the user's ID. - Database Update: Once the upload is successful, call an API route to update the
avatar_url field in your users table with the new URL.
This ensures the image is persisted in storage and the reference is saved in your database.
// High-level flow:
// 1. Upload file to Supabase Storage
const { imageUrl: uploadedImageUrl, error } = await uploadImage({
file: imageFile,
bucket: 'avatar',
folder: user.id,
});
// 2. Update database via API
await fetch('/api/update-avatar', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ userId: user.id, avatarUrl: uploadedImageUrl }),
});