A drop zone for React whose files upload themselves to Upstash Blob. Same
prop getters as react-dropzone, but instead of a
File[] you get a live list of uploads with progress, previews, errors and the stored blobs.
npm install @upstash/react-dropzone @upstash/blobexamples/nextjs is a Next.js app with a styled dropzone you can copy
(components/dropzone.tsx): drag states, thumbnails,
progress, pause and resume for large files, cancel, retry and remove. Its pages show a multi-file
dropzone with a full-page drop toggle, a single-image avatar route with its own limits, and a form
that uploads on submit. It runs on this repo's build, so build the package first, then create a
bucket with the Upstash CLI:
pnpm install && pnpm build
cd examples/nextjs
upstash blob create --name react-dropzone-example --visibility public --write-env .env.local
pnpm install && pnpm devThe route is the @upstash/blob upload handler, unchanged. It decides who may upload, where the
file goes, and which types and sizes it takes; the dropzone reads those limits from it.
// lib/uploads.ts
import 'server-only';
import { BlobError, uniquePath, uploadHandler } from '@upstash/blob';
export const uploads = uploadHandler({
constraints: { maxSize: '20mb', contentTypes: ['image/*', 'application/pdf'] },
onBeforeUpload: async ({ request, file }) => {
const user = await getUser(request);
if (!user) throw new BlobError('unauthorized'); // the 401; nothing is signed
return { path: uniquePath(`${user.id}/${file.name}`), metadata: { owner: user.id } };
},
onUploadComplete: async ({ metadata, url, uploadId }) => {
await sql`insert into files (upload_id, owner, url)
values (${uploadId}, ${metadata.owner}, ${url})
on conflict (upload_id) do nothing`;
return { uploadId };
},
});// app/api/upload/route.ts
import { uploads } from '@/lib/uploads';
export const { GET, POST } = uploads;The handler reads UPSTASH_BLOB_TOKEN. Its options (routes, context, input, multipart, bucket
CORS) are in the @upstash/blob README.
Bind the hook to the handler's type once:
// lib/dropzone.ts
'use client';
import { dropzoneHooks } from '@upstash/react-dropzone';
import type { uploads } from './uploads';
export const { useDropzone } = dropzoneHooks<typeof uploads>();Then use it anywhere:
'use client';
import { useDropzone } from '@/lib/dropzone';
export function Attachments() {
const { getRootProps, getInputProps, isDragActive, uploads } = useDropzone();
return (
<div {...getRootProps()} className={isDragActive ? 'zone active' : 'zone'}>
<input {...getInputProps()} />
<p>Drop files here, or click to pick them</p>
{uploads.map((u) => (
<div key={u.id}>
{u.preview && <img src={u.preview} alt="" width={40} />}
{u.file.name} {u.status === 'error' ? u.error.message : `${u.percent}%`}
{u.pending && <button onClick={u.cancel}>Cancel</button>}
</div>
))}
</div>
);
}blob.data is typed from onUploadComplete: here u.blob.data.uploadId is a string once
u.status === 'done'. The unbound form takes the handler's URL: useDropzone('/api/upload'), with
blob.data as unknown.
Swap the import and delete the upload code:
- import { useDropzone } from 'react-dropzone';
+ import { useDropzone } from '@/lib/dropzone';
- const [files, setFiles] = useState([]);
- const onDrop = useCallback(async (accepted) => {
- for (const file of accepted) {
- const { url } = await fetch('/api/sign', { method: 'POST', body: file.name }).then((r) => r.json());
- await fetch(url, { method: 'PUT', body: file });
- }
- }, []);
- const { getRootProps, getInputProps, isDragActive, acceptedFiles, fileRejections } = useDropzone({
- onDrop,
- accept: { 'image/*': [] },
- maxSize: 20_000_000,
- });
+ const { getRootProps, getInputProps, isDragActive, uploads } = useDropzone();accept,maxSizeandminSizeare gone from the client: the route'sconstraintsare the limits, served by itsGETand applied to the drop, the drag state and the picker'saccept.acceptedFilesandfileRejectionsbecome one array,uploads, in drop order. A refused file (empty, wrong type, too big, overmaxFiles, failedvalidator) is a record withstatus: 'error'.- The prop getters,
open,rootRef,inputRef, the drag, focus and dialog flags, paste, folder drops and keyboard activation work as they do there.
Each record in uploads holds:
| Field | |
|---|---|
id |
Stable key for the row. |
file |
The dropped File. |
status |
'idle' (held, see autoUpload), 'queued', 'uploading', 'paused', 'finishing', 'done', 'canceled' or 'error'. |
percent, loaded, total |
Progress of this file. |
pending |
Queued, uploading, finishing or paused. |
blob |
On 'done': the stored blob (path, url, size, contentType, ...) and data, what onUploadComplete returned. |
error |
On 'error': a BlobError with a code (content_type_not_allowed, too_large, empty_body, invalid_input, unauthorized, ...) and a readable message. |
preview |
For non-empty image files: an object URL to show the image, revoked when the record is cleared or the hook unmounts. |
cancel(), retry(), pause(), resume() |
Each returns whether it did anything. Only uploads over the route's multipart threshold (16 MB unless the route says otherwise) can pause. |
Everything useUpload from @upstash/blob/react takes, plus:
| Option | Default | |
|---|---|---|
input |
The route's input, or (file) => input. Required, by the types, exactly when the route has an input schema. |
|
autoUpload |
true |
When false, dropped files wait as 'idle' until startIdle(). |
fullPage |
false |
The whole window is the drop target. The root element stays the click and keyboard target. |
onChange |
(blobs) => void, whenever the set of finished uploads changes. |
|
maxFiles |
0 |
Most files the list holds at once, failed and canceled ones not counted. 0 is no limit. retry() on a failed upload answers false while the list is full. |
multiple |
true |
false takes one file per drop or pick. |
validator |
(file) => null | string | { code, message }, may be async. null, undefined, true or [] accepts the file; false, a message, or { code, message } (or a list of them) refuses it. The record's error.code is invalid_input, and error.cause is the list of { code, message } returned, so error.cause[0].code is your own code. |
|
disabled, noClick, noKeyboard, noDrag, noPaste |
false |
Turn off one way in. |
noDragEventsBubbling |
false |
Keep drag events from reaching a parent dropzone. |
preventDropOnDocument |
true |
Stop a file dropped beside the zone from opening in the tab. |
autoFocus |
false |
Focus the root on mount, so paste works straight away. |
onDragEnter, onDragOver, onDragLeave |
Drag events that carry files. | |
onDrop |
(accepted, refused, event): the files that will upload and the refused records. Informational; the upload already started. |
|
onDone, onError |
Per upload. onError also runs for files refused on the drop. |
|
endpoint, headers, concurrency |
'/api/upload', none, 3 |
As in useUpload. |
| Field | |
|---|---|
getRootProps(props?), getInputProps(props?) |
Spread on the drop element and its <input>. Pass your own handlers through them. |
uploads |
Every dropped file, see above. upload is the newest. |
blobs |
The stored blobs of the finished uploads, in order. |
isUploading, progress |
Some upload is in flight; 0 to 100 across the uploads started since the list was last idle. |
isDragActive, isDragAccept, isDragReject |
A file drag is over the zone, and whether the route would take it (type and maxFiles; size is only known on the drop). With a validator, neither accept nor reject until the drop. |
isFocused, isFileDialogActive |
|
open() |
Opens the file picker. |
startIdle(id?) |
Sends one held upload, or all of them. A sent row keeps its id. |
start({ files, input }) |
Uploads files from anywhere into the same list. |
clear(id?) |
Removes one record, or all. A running upload keeps going. |
accept, constraints |
What the route serves. |
rootRef, inputRef |
export const uploads = uploadHandler({
onBeforeUpload: async ({ request, route, file }) => { /* ... */ },
routes: {
avatar: { constraints: { contentTypes: ['image/*'], maxSize: '2mb' } },
attachment: { constraints: { maxSize: '100mb' } },
},
});const avatar = useDropzone('avatar', { multiple: false });
const attachments = useDropzone('attachment', { maxFiles: 10 });A route name that does not exist, or a missing one, is a type error.
onChange hands over the finished blobs, so the dropzone can back a form value:
const [paths, setPaths] = useState<string[]>([]);
const { getRootProps, getInputProps, uploads, isUploading } = useDropzone({
maxFiles: 5,
onChange: (blobs) => setPaths(blobs.map((b) => b.path)),
});
<form action={save}>
<div {...getRootProps()}>
<input {...getInputProps()} />
{uploads.map((u) => <Row key={u.id} upload={u} />)}
</div>
<input type="hidden" name="paths" value={paths.join(',')} />
<button disabled={isUploading}>Save</button>
</form>;With autoUpload: false nothing is sent on the drop. Files sit in uploads as 'idle' (with their
previews, and refusals already shown), cancel() takes one out, and startIdle() sends the rest:
const { getRootProps, getInputProps, uploads, startIdle } = useDropzone({
autoUpload: false,
input: () => ({ albumId }),
});
<button onClick={() => startIdle()}>Upload {uploads.filter((u) => u.status === 'idle').length} files</button>;An input function is read when each file is sent, so it sees the form as it is at that moment.
const { getRootProps, getInputProps, isDragActive } = useDropzone({ fullPage: true });
<>
{isDragActive && <div className="overlay">Drop to upload</div>}
<button {...getRootProps()}>
<input {...getInputProps()} />
Upload
</button>
</>;Drag state and drops work anywhere on the page; the button opens the picker.
- Types are checked on the drop against the route's served
contentTypes, read as the route reads them (image/jpgisimage/jpeg, a file with no type isapplication/octet-stream), and sizes against itsmaxSize, for held files too. Before the route'sGETanswers, files are sent and the route decides; a file held before then is checked whenstartIdle()sends it. The route checks again either way. - An empty file is refused on the drop (
empty_body), limits or not: the route never takes one. - A file in a dropped folder that the browser cannot read is listed as refused (
invalid_input) under its name; the rest of the drop still lands. - Clicks on a button, link or input inside the root are left to that control, so a cancel button in the upload list does not also open the picker.
- The package is marked
'use client'and touches no browser global on import, so it is safe to import from files that also render on the server. - Requires React 18 or later and
@upstash/blob0.0.14 or later.
MIT