To upload an image from React, check the file in the browser, send it as multipart/form-data to a storage API, save the returned path on a database row, and show it through a URL. With WoWSQL you create a bucket (public for avatars, private for receipts), POST the file to the documented storage endpoint and display it at /storage/v1/object/public/{bucket}/{path}. You don't need your own upload server. This guide builds an avatar uploader that shrinks photos before they leave the phone, and it covers one SDK pitfall you'll hit in the browser.
The React component below was built with Vite 8 and React 19 and run in headless Chrome against a local mock of the WoWSQL storage API, to check the exact request it sends. The server-side snippets were type-checked and run against the same kind of mock using @wowsql/sdk 3.10.0 (the current npm release on 28 November 2026). Nothing here was run against a live WoWSQL project, so test on a scratch project before you ship.
Key facts
- Buckets: public or private. Public is a setting on the bucket, not on each file. Files in a public bucket are served without auth at
https://<project>.wowsqlconnect.com/storage/v1/object/public/{bucket}/{path}(storage docs).- API: create, list, update and delete buckets; upload (multipart), list, download and delete files; usage stats. Endpoints live under
/api/v1/storage/projects/{project_slug}on your project host.- No presigned URLs: the docs say WoWSQL storage does not issue them, and the old S3 add-on routes return
410 Gone. Private files are downloaded with an API key.- SDK:
@wowsql/sdk3.10.0 has aWowSQLStorageclass. Itsupload()method fails in the browser withReferenceError: Buffer is not defined(we reproduced this in Chrome), so this guide uploads withfetchin the browser and uses the SDK on the server.- Plan limits (pricing, checked 28 November 2026): Free has 512 MB of file storage and 5 GB of bandwidth. Pro ($25/month) has 100 GB of files and 100 GB of bandwidth, then storage from $0.25/GB and transfer from $0.10/GB. Scale ($99/month) has 500 GB of files.
How image upload works
- The user picks a photo in an
<input type="file">. - Your React code checks the type and size, then resizes the photo on the device.
- The browser POSTs the file to the storage API with your project's anon key.
- You build the public URL from the bucket and path, and save the path on the user's row.
- Your pages render
<img src={url}>. For private files, a server checks the user first.
The resize step is not optional in practice. WoWSQL's storage docs don't describe on-the-fly image transforms, so whatever you upload is what every visitor downloads. A 4 MB phone photo used as a 96-pixel avatar wastes bandwidth on both sides.
Storage options compared
| WoWSQL Storage | Supabase Storage | Cloud Storage for Firebase | |
|---|---|---|---|
| Free plan | 512 MB files, 5 GB bandwidth | 1 GB files, 5 GB egress (pricing) | Needs the pay-as-you-go Blaze plan since September 2024; no-cost usage still applies on Blaze (Firebase FAQ) |
| Largest single file | Per-bucket file_size_limit; no per-file maximum is published |
50 MB on Free, up to 500 GB on Pro (file limits) | Not listed on the pages we checked |
| Signed or presigned URLs | No (docs) | Yes, time-limited signed URLs | Download URLs via getDownloadURL() (docs) |
| Image transforms | Not in the storage API docs | Yes, Pro plan and above (docs) | Through the Resize Images extension |
| Resumable uploads | Not in the storage API docs | Yes (TUS) | Yes, uploadBytesResumable() (docs) |
| Access control | Public/private bucket plus your API key | Postgres RLS policies on every file operation (docs) | Security Rules |
| Paid storage overage | From $0.25/GB | $0.0213/GB on Pro | Google Cloud rates |
Competitor details were read on 28 November 2026. Supabase is clearly ahead on storage features: signed URLs, image transformations, resumable uploads, storage policies and much cheaper overage per GB. If your app needs those today, use Supabase or put a CDN or image service in front of your files. WoWSQL fits when you want simple public and private buckets in the same project as your Postgres tables, auth and realtime, with a region in Mumbai, US East or Frankfurt.
Step 1: Create the buckets
Make one public bucket for avatars and one private bucket for anything personal. Use the dashboard, or run this once from your machine with the service key. The service key bypasses all access rules, so it must never reach a browser.
// storage-server.ts (Node 18+), server only
import { WowSQLStorage, ProjectAuthClient } from '@wowsql/sdk'
const PROJECT_URL = process.env.WOWSQL_URL! // https://myproject.wowsqlconnect.com
const SERVICE_KEY = process.env.WOWSQL_SERVICE_KEY! // wowsql_service_...
const ANON_KEY = process.env.WOWSQL_ANON_KEY! // wowsql_anon_...
const admin = new WowSQLStorage({ projectUrl: PROJECT_URL, apiKey: SERVICE_KEY })
const auth = new ProjectAuthClient({ projectUrl: PROJECT_URL, apiKey: ANON_KEY })
export async function setupBuckets() {
await admin.createBucket('avatars', {
public: true,
allowedMimeTypes: ['image/jpeg', 'image/png', 'image/webp'],
})
await admin.createBucket('receipts', { public: false })
}
Buckets also take a file_size_limit. The docs don't state its unit, so set it in the dashboard and test it with an oversized file rather than guessing.
Step 2: A small upload helper for the browser
Put your project URL and anon key in .env.local. Vite exposes only variables that start with VITE_, and anything exposed this way is public, which is fine for the anon key and never fine for the service key.
VITE_WOWSQL_URL=https://myproject.wowsqlconnect.com
VITE_WOWSQL_ANON_KEY=wowsql_anon_...
// src/lib/storage.ts
const PROJECT_URL = import.meta.env.VITE_WOWSQL_URL
const ANON_KEY = import.meta.env.VITE_WOWSQL_ANON_KEY
const SLUG = new URL(PROJECT_URL).hostname.split('.')[0] // "myproject"
const API = `${PROJECT_URL}/api/v1/storage/projects/${SLUG}`
const headers = { apikey: ANON_KEY, Authorization: `Bearer ${ANON_KEY}` }
export type StoredFile = { path: string; name: string; size: number; mime_type: string | null }
export async function uploadImage(bucket: string, folder: string, file: File, fileName: string): Promise<StoredFile> {
const form = new FormData()
form.append('file', file, fileName) // stored as <folder>/<fileName>
const res = await fetch(`${API}/buckets/${bucket}/files?folder=${encodeURIComponent(folder)}`, {
method: 'POST',
headers, // no Content-Type: the browser sets the multipart boundary
body: form,
})
if (res.status === 413) throw new Error('File or project storage limit exceeded')
if (!res.ok) throw new Error(`Upload failed (${res.status}): ${await res.text()}`)
return res.json()
}
export function publicUrl(bucket: string, path: string): string {
return `${PROJECT_URL}/storage/v1/object/public/${bucket}/${path}`
}
Two details that cost people time. First, don't set Content-Type yourself: the browser has to add the multipart boundary. Second, the stored path is the folder query parameter plus the file name inside the form data. The SDK behaves the same way: its third argument only sets the folder, so pass the fourth argument if you want to control the stored name.
Why not WowSQLStorage.upload() in React?
In @wowsql/sdk 3.10.0, upload() begins with fileData instanceof Buffer. Buffer exists in Node but not in browsers, and Vite doesn't polyfill it. In our Chrome test the call threw ReferenceError: Buffer is not defined before any request was sent. The SDK's other storage methods and upload() itself work in Node. Until a fixed release ships, use the fetch helper above in browser code.
Step 3: Resize the photo before upload
// src/lib/resize.ts: longest side <= maxSide, re-encoded as WebP
export async function resizeImage(file: File, maxSide = 512, quality = 0.85): Promise<Blob> {
const bitmap = await createImageBitmap(file)
const scale = Math.min(1, maxSide / Math.max(bitmap.width, bitmap.height))
const canvas = document.createElement('canvas')
canvas.width = Math.round(bitmap.width * scale)
canvas.height = Math.round(bitmap.height * scale)
canvas.getContext('2d')!.drawImage(bitmap, 0, 0, canvas.width, canvas.height)
bitmap.close()
return new Promise((resolve, reject) =>
canvas.toBlob(b => (b ? resolve(b) : reject(new Error('Could not encode image'))), 'image/webp', quality),
)
}
In our headless Chrome run, a 2000 × 1500 PNG test image left the browser as a 512 × 384 WebP. Real photos compress differently, so check sizes with your own images.
Step 4: The avatar component
// src/AvatarUpload.tsx
import { useEffect, useState, type ChangeEvent } from 'react'
import { uploadImage, publicUrl } from './lib/storage'
import { resizeImage } from './lib/resize'
const BUCKET = 'avatars'
const MAX_BYTES = 10 * 1024 * 1024 // reject huge originals before resizing
const ALLOWED = ['image/jpeg', 'image/png', 'image/webp']
export function AvatarUpload({ userId, onUploaded }: { userId: string; onUploaded?: (url: string) => void }) {
const [preview, setPreview] = useState<string | null>(null)
const [url, setUrl] = useState<string | null>(null)
const [error, setError] = useState<string | null>(null)
const [busy, setBusy] = useState(false)
// free the local preview when it is replaced or the component unmounts
useEffect(() => () => { if (preview) URL.revokeObjectURL(preview) }, [preview])
async function onFileChange(e: ChangeEvent<HTMLInputElement>) {
const file = e.target.files?.[0]
e.target.value = '' // let the user pick the same file again
if (!file) return
setError(null)
if (!ALLOWED.includes(file.type)) return setError('Use a JPG, PNG or WebP image.')
if (file.size > MAX_BYTES) return setError('Images must be 10 MB or smaller.')
setPreview(URL.createObjectURL(file))
setBusy(true)
try {
const small = await resizeImage(file) // ~512 px WebP
const fileName = `avatar-${Date.now()}.webp` // new name each time, so caches never serve the old one
const folder = `users/${userId}`
await uploadImage(BUCKET, folder, new File([small], fileName, { type: 'image/webp' }), fileName)
const link = publicUrl(BUCKET, `${folder}/${fileName}`)
setUrl(link)
onUploaded?.(link) // e.g. save the path on the user's profile row
} catch (err) {
setError(err instanceof Error ? err.message : 'Upload failed')
} finally {
setBusy(false)
}
}
return (
<div>
<input type="file" accept={ALLOWED.join(',')} onChange={onFileChange} disabled={busy} />
{busy && <p>Uploading…</p>}
{error && <p role="alert">{error}</p>}
{(url ?? preview) && <img src={url ?? preview!} alt="Your avatar" width={96} height={96} />}
</div>
)
}
The accept attribute and type check are only for user experience: anyone can send any bytes to your API, which is why the bucket also has allowed_mime_types. Pick a new file name on every upload. WoWSQL's storage policy says public URLs may be cached at the edge, including by Cloudflare, so an overwritten file can keep showing the old image for a while.
Save the path (for example users/u_123/avatar-1732771200000.webp) on the user's row rather than the full URL. If you move to a custom domain later (custom domains come with the Scale plan), you only change how you build the URL.
Step 5: Keep private files private
A public bucket is right for avatars and product photos. Receipts, ID documents and medical files belong in a private bucket. The anon key ships inside your JavaScript bundle, so treat it as public: the storage docs don't describe per-user storage policies, and they don't offer presigned URLs. The safe pattern is a small server route (your own backend, or an Edge Function on Pro) that checks the signed-in user and then fetches the file with the service key:
// continues storage-server.ts
export async function downloadOwnReceipt(accessToken: string, fileName: string): Promise<ArrayBuffer> {
if (!/^[\w.-]+$/.test(fileName)) throw new Error('Bad file name')
const user = await auth.getUser(accessToken) // rejects an invalid or expired token
return admin.download('receipts', `users/${user.id}/${fileName}`)
}
The file-name check stops ../ tricks, and the path is built from the verified user ID, never from anything the browser sends. Send the result back with the right Content-Type and Cache-Control: private.
Step 6: Clean up old files
Each new avatar leaves the previous one behind. Prune them on the server after a successful upload, and delete a user's folder when they delete their account:
export async function pruneOldAvatars(userId: string) {
const files = await admin.listFiles('avatars', { prefix: `users/${userId}/`, limit: 100 })
const stale = files.sort((a, b) => b.created_at.localeCompare(a.created_at)).slice(1)
for (const f of stale) await admin.deleteFile('avatars', f.path)
return stale.length
}
Free projects become read-only when they pass a limit (reads and deletes still work), so a forgotten pile of old uploads can block new ones. admin.getStats() returns file counts and bytes if you want a usage check in your admin panel.
Before you ship
- Test a 0-byte file, a renamed
.exe, a 20 MB photo and a slow 3G connection (Chrome DevTools can throttle). - Show progress text and allow a retry. A plain
fetchupload restarts from zero if the connection drops. - Free plan projects get no platform backups (see backups). Pro and Scale get daily backups kept for 7 days. Keep originals elsewhere if losing them would hurt.
- Go through the BaaS security checklist: the service key stays on servers, and RLS stays on for tables.
Related guides
- File storage for apps: what to choose
- The best backend for a React app
- How to add login to your app
- Mobile app backend for India: latency, OTP and data costs
- Firestore to Postgres: model documents as tables
FAQ
How do I upload an image from React to cloud storage?
Validate the file in an input change handler, optionally resize it with a canvas, then POST it as multipart form data to your storage provider's upload endpoint. With WoWSQL that is /api/v1/storage/projects/{slug}/buckets/{bucket}/files?folder=... on your project host. Then save the returned path on a database row and render the public URL.
Can I upload files directly from the browser without my own server?
Yes, for public content such as avatars. The browser sends the file with your anon key, which is designed to be public. For private files, add a small server route that checks the user's token and uses the service key, because WoWSQL storage has no presigned URLs.
Should user avatars go in a public or private bucket?
Public, in most apps. Profile photos are meant to be seen, and a public bucket lets you use a plain URL in <img> tags. Use a private bucket for anything a stranger shouldn't open: receipts, ID scans, invoices or chat attachments.
Does WoWSQL support presigned or signed upload URLs?
No. WoWSQL's storage docs say it does not issue presigned URLs, and the retired S3 add-on routes return 410 Gone. Use a public bucket for openly shared files, or serve private files through your own server code.
Why does WowSQLStorage.upload() say "Buffer is not defined" in React?
In @wowsql/sdk 3.10.0, upload() checks fileData instanceof Buffer, and Buffer is a Node global that browsers don't have. We reproduced the error in Chrome with a Vite build. Use a fetch call to the documented upload endpoint in the browser, and use the SDK in Node.
How big can uploaded images be on WoWSQL?
The plan sets the total: 512 MB of files on Free, 100 GB on Pro and 500 GB on Scale. Each bucket can also have a file size limit and allowed MIME types. WoWSQL doesn't publish a single per-file maximum, so test your largest expected file, and resize images on the client anyway.
How do I resize an image in React before uploading?
Draw it onto a canvas at the target size with createImageBitmap and drawImage, then call canvas.toBlob(callback, 'image/webp', 0.85). Wrap the blob in a File and upload that. The resize helper in this guide does exactly that.