Generated Components
All of the generateX
functions takes an optional configuration object:
export interface GenerateTypedHelpersOptions {
/**
* URL to the UploadThing API endpoint
* @example "/api/uploadthing"
* @example "https://www.example.com/api/uploadthing"
*
* If relative, host will be inferred from either the `VERCEL_URL` environment variable or `window.location.origin`
*
* @default (VERCEL_URL ?? window.location.origin) + "/api/uploadthing"
*/
url?: string | URL;
}
generateComponents
As of v6.2.1
, the generateComponents
function has been deprecated in favor
of the generateUploadButton
and generateUploadDropzone
functions to
improve tree-shaking.
The generateComponents
function is used to generate the UploadButton and
UploadDropzone components you use to interact with UploadThing. Generating
components allows for fully typesafe components bound to the type of your file
router.
import { generateComponents } from "@uploadthing/react";
import type { OurFileRouter } from "~/app/api/uploadthing/core";
export const { UploadButton, UploadDropzone } =
generateComponents<OurFileRouter>();
generateUploadButton
The generateUploadButton
function is used to generate the UploadButton
component you use to interact with UploadThing. Generating components allows for
fully typesafe components bound to the type of your file router.
import { generateUploadButton } from "@uploadthing/react";
export const UploadButton = generateUploadButton<OurFileRouter>();
generateUploadDropzone
The generateUploadDropzone
function is used to generate the UploadDropzone
component you use to interact with UploadThing. Generating components allows for
fully typesafe components bound to the type of your file router.
import { generateUploadDropzone } from "@uploadthing/react";
export const UploadDropzone = generateUploadDropzone<OurFileRouter>();
UploadButton
A simple button that opens the native file picker and uploads the selected files. The default button is shown below. See Theming on how to customize it.
import { UploadButton } from "@uploadthing/react";
import { OurFileRouter } from "./api/uploadthing/core";
export const OurUploadButton = () => (
<UploadButton<OurFileRouter>
endpoint="imageUploader"
onClientUploadComplete={(res) => {
// Do something with the response
console.log("Files: ", res);
alert("Upload Completed");
}}
onUploadError={(error: Error) => {
// Do something with the error.
alert(`ERROR! ${error.message}`);
}}
onBeforeUploadBegin={(files) => {
// Preprocess files before uploading (e.g. rename them)
return files.map(
(f) => new File([f], "renamed-" + f.name, { type: f.type }),
);
}}
onUploadBegin={(name) => {
// Do something once upload begins
console.log("Uploading: ", name);
}}
onChange={(acceptedFiles) => {
// Do something with the accepted files
console.log("Accepted files: ", acceptedFiles);
}}
/>
);
Configuration
Prop | Type | Required | Notes | Description |
---|---|---|---|---|
<FileRouter> | generic | Yes | The type from the FileRouter you defined in your backend | |
endpoint | string | Yes | The name of the route you want this button to upload to | |
url | string | URL | No | Added in v6.0 | The url to where you are serving your uploadthing file router, required if you're not serving from /api/uploadthing |
input | string | If set on the fileroute | Added in v5.0 | Object matching the input schema that was set for this endpoint in your File Router |
headers | HeadersInit | (() => MaybePromise\<HeadersInit\>) | No | Added in v6.4 | Send custom headers with the API requests to your server. Primarily for authentication when using a separate backend. |
skipPolling | boolean | No | Added in v6.3 | Skip polling for server data. Defaults to true if no onClientUploadComplete is set, else false . |
onClientUploadComplete | (res: UploadedFileResponse[]) => void | No | callback function that runs after the serverside onUploadComplete callback. | |
onUploadError | function | No | callback function when upload fails | |
onUploadAborted | function | No | Added in v6.7 | callback function when upload is aborted |
onUploadProgress | function | No | Added in v5.1 | callback function for upload progress |
onBeforeUploadBegin | (files: File[]) => File[] | No | Added in v6.0 | callback function called before uploading starts. The files returned are the files that will be uploaded |
onUploadBegin | function | No | Added in v5.4 | callback function for upload begin |
config | Config | No | Added in v5.7 | object to pass additional configuration for button |
disabled | boolean | No | Added in v6.7 | Disables the button. |
onChange | (files: File[]) => void | No | Added in v6.8 | Callback function that runs when files are selected. Note: files is an array containing all selected files, not just the latest ones. |
Config object
Attribute | Type | Required | Notes | Description |
---|---|---|---|---|
mode | 'auto' | 'manual' | No | Added in v5.4 | mode of button. 'auto' is default one and triggers upload right after selection. 'manual' requires an additional click to start the upload |
appendOnPaste | boolean | No | Added in v5.7 | enables ability to paste files from clipboard |
If you want to disable the button based on when your input
is not satisfied,
you can place your validator in a shared file, so that you can import it in
both the server-side .input()
and on the client-side for your disabled
prop logic.
The interface for UploadFileResponse
is:
export type UploadFileResponse<TServerOutput> = {
name: string;
size: number;
key: string;
url: string; // e.g. `https://utfs.io/f/abc-123.txt`
appUrl: string; // e.g. `https://utfs.io/a/app-1/abc-123.txt`
// Matches what's returned from the serverside `onUploadComplete` callback
// Will be `null` if `skipPolling` is set to `true`.
serverdata: TServerOutput;
};
For the difference of the two URLs, see Accessing Files.
UploadDropzone
A react-dropzone
powered dropzone that let's you drag and drop files to
upload. The default dropzone is shown below. See Theming on how to
customize it.
import { UploadDropzone } from "@uploadthing/react";
import { OurFileRouter } from "./api/uploadthing/core";
export const OurUploadDropzone = () => (
<UploadDropzone<OurFileRouter>
endpoint="withoutMdwr"
onClientUploadComplete={(res) => {
// Do something with the response
console.log("Files: ", res);
alert("Upload Completed");
}}
onUploadError={(error: Error) => {
alert(`ERROR! ${error.message}`);
}}
onUploadBegin={(name) => {
// Do something once upload begins
console.log("Uploading: ", name);
}}
onChange={(acceptedFiles) => {
// Do something with the accepted files
console.log("Accepted files: ", acceptedFiles);
}}
/>
);
Configuration
Prop | Type | Required | Notes | Description |
---|---|---|---|---|
<FileRouter> | generic | Yes | The type from the FileRouter you defined in your backend | |
endpoint | string | Yes | The name of the route you want this button to upload to | |
url | string | URL | No | Added in v6.0 | The url to where you are serving your uploadthing file router, required if you're not serving from /api/uploadthing |
input | string | If set on the fileroute | Added in v5.0 | Object matching the input schema that was set for this endpoint in your File Router |
headers | HeadersInit | (() => MaybePromise\<HeadersInit\>) | No | Added in v6.4 | Send custom headers with the API requests to your server. Primarily for authentication when using a separate backend. |
skipPolling | boolean | No | Added in v6.3 | Skip polling for server data. Defaults to true if no onClientUploadComplete is set, else false . |
onClientUploadComplete | (res: UploadedFileResponse[]) => void | No | callback function that runs after the serverside onUploadComplete callback. | |
onUploadError | function | No | callback function when upload fails | |
onUploadAborted | function | No | Added in v6.7 | callback function when upload is aborted |
onUploadProgress | function | No | Added in v5.1 | callback function for upload progress |
onBeforeUploadBegin | (files: File[]) => File[] | No | Added in v6.0 | callback function called before uploading starts. The files returned are the files that will be uploaded |
onUploadBegin | function | No | Added in v5.4 | callback function for upload begin |
config | object | No | Added in v5.4 | object to pass additional configuration for dropzone |
disabled | boolean | No | Added in v6.7 | Disables the dropzone. |
onChange | (acceptedFiles: File[]) => void | No | Added in v6.8 (onDrop in v6.5-v-6.7 ) | Callback called when files are dropped or pasted. |
Config object
Attribute | Type | Required | Notes | Description |
---|---|---|---|---|
mode | 'auto' | 'manual' | No | Added in v5.4 | mode of dropzone. 'manual' is default one. 'auto' triggers upload right after selection |
appendOnPaste | boolean | No | Added in v5.7 | enables ability to paste files from clipboard |
If you want to disable the dropzone based on when your input
is not
satisfied, you can place your validator in a shared file, so that you can
import it in both the server-side .input()
and on the client-side for your
disabled
prop logic.
generateReactHelpers
The generateReactHelpers
function is used to generate the useUploadThing hook
and the uploadFiles functions you use to interact with UploadThing in custom
components. It takes your File Router as a generic
import { generateReactHelpers } from "@uploadthing/react";
import type { OurFileRouter } from "~/app/api/uploadthing/core";
export const { useUploadThing, uploadFiles } =
generateReactHelpers<OurFileRouter>();
Configuration
Prop | Type | Required | Notes | Description |
---|---|---|---|---|
url | string | URL | No | Added in v6.0 | The url to where you are serving your uploadthing file router, required if you're not serving from /api/uploadthing |
useDropzone
Added in
v5.6
This hook is currently a minified fork of react-dropzone (opens in a new tab) with better ESM support. See their docs (opens in a new tab) for reference.
You can import the minified hook from @uploadthing/react
. If you need access
to any of the removed APIs, you should import the original hook from
react-dropzone
.
This hook isn't strictly covered by semver as we might make changes to tailor it to our needs in a future minor release. Migration guides will be provided if this happens.
useUploadThing
This hook provides a function to start uploading, an isUploading
state, and
the permittedFileInfo
which gives information about what file types, sizes and
counts are allowed by the endpoint. See example below for a simple dropzone
using the useDropzone
and useUploadThing
hooks. For a more complete example,
take a look at
our provided components (opens in a new tab)
// Note: `useUploadThing` is IMPORTED FROM YOUR CODEBASE using the `generateReactHelpers` function
import { useDropzone } from "@uploadthing/react";
import { generateClientDropzoneAccept } from "uploadthing/client";
import { useUploadThing } from "~/utils/uploadthing";
export function MultiUploader() {
const [files, setFiles] = useState<File[]>([]);
const onDrop = useCallback((acceptedFiles: File[]) => {
setFiles(acceptedFiles);
}, []);
const { startUpload, permittedFileInfo } = useUploadThing(
"myUploadEndpoint",
{
onClientUploadComplete: () => {
alert("uploaded successfully!");
},
onUploadError: () => {
alert("error occurred while uploading");
},
onUploadBegin: () => {
alert("upload has begun");
},
},
);
const fileTypes = permittedFileInfo?.config
? Object.keys(permittedFileInfo?.config)
: [];
const { getRootProps, getInputProps } = useDropzone({
onDrop,
accept: fileTypes ? generateClientDropzoneAccept(fileTypes) : undefined,
});
return (
<div {...getRootProps()}>
<input {...getInputProps()} />
<div>
{files.length > 0 && (
<button onClick={() => startUpload(files)}>
Upload {files.length} files
</button>
)}
</div>
Drop files here!
</div>
);
}
Configuration
const { startUpload, isUploading, permittedFileInfo } = useUploadThing(
endpoint,
opts: {
onClientUploadComplete: ({fileKey: string, fileUrl: string}[]) => void
onUploadError: (error: Error) => void
onUploadAborted: () => void
onUploadProgress: (progress: number) => void
onUploadBegin: (fileName: string) => void
},
);
endpoint
: The name of the route you want this button to upload to
Option | Type | Required | Notes | Description |
---|---|---|---|---|
headers | HeadersInit | (() => MaybePromise\<HeadersInit\>) | No | Added in v6.4 | Send custom headers with the API requests to your server. Primarily for authentication when using a separate backend. |
skipPolling | boolean | No | Added in v6.3 | Skip polling for server data. |
onClientUploadComplete | (res: UploadedFileResponse[]) => void | No | callback function that runs after the serverside onUploadComplete callback. | |
onUploadError | function | No | callback function when upload fails | |
onUploadProgress | function | No | Added in v5.1 | callback function for upload progress |
onBeforeUploadBegin | (files: File[]) => File[] | No | Added in v5.8 | callback function called before uploading starts. The files returned are the files that will be uploaded |
onUploadBegin | function | No | Added in v5.4 | callback function for upload begin |
signal | AbortSignal | No | Added in v6.7 | Abort signal to abort the upload |
Returns
Prop | Type | Description |
---|---|---|
startUpload | function | (files: File[], input?: TInput) => void function to start a file upload. TInput is inferred from what you've defined on the fileroute on the backend. |
isUploading | function | if file(s) are currently uploading |
permittedFileInfo | function | information on permitted file types, sizes, and counts |
uploadFiles
// Note: this is IMPORTED FROM YOUR CODEBASE using the `generateReactHelpers` function
import { uploadFiles } from "~/utils/uploadthing";
const uploadSomeFiles = async () => {
const files = [
new File(["foo"], "foo.txt", {
type: "text/plain",
}),
];
const res = await uploadFiles("yourEndpoint", {
files,
input: {}, // will be typesafe to match the input set for `imageUploader` in your FileRouter
});
};
Configuration
uploadFiles(endpoint: string, opts: {
files: File[],
input?: {} // will be typesafe to match the input set for `endpoint` in your FileRouter
})
Arguments | Type | Required | Notes | Description |
---|---|---|---|---|
files | File[] | Yes | The files you intend to upload | |
endpoint | string | Yes | The name of the route you want to upload to | |
input | string | If set on the fileroute | Added in v5.0 | Object matching the input schema that was set for this endpoint in your File Router |