API Reference
React

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.

utils/uploadthing.tsx
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.

utils/uploadthing.tsx
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.

utils/uploadthing.tsx
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.

Allowed content
app/example-uploader.tsx
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);
    }}
  />
);

Configuration

PropTypeRequiredNotesDescription
<FileRouter>genericYesThe type from the FileRouter you defined in your backend
endpointstringYesThe name of the route you want this button to upload to
urlstring | URLNoAdded in v6.0The url to where you are serving your uploadthing file router, required if you're not serving from /api/uploadthing
inputstringIf set on the filerouteAdded in v5.0Object matching the input schema that was set for this endpoint in your File Router
headersHeadersInit | (() => MaybePromise\<HeadersInit\>)NoAdded in v6.4Send custom headers with the API requests to your server. Primarily for authentication when using a separate backend.
skipPollingbooleanNoAdded in v6.3Skip polling for server data. Defaults to true if no onClientUploadComplete is set, else false.
onClientUploadComplete(res: UploadedFileResponse[]) => voidNocallback function that runs after the serverside onUploadComplete callback.
onUploadErrorfunctionNocallback function when upload fails
onUploadAbortedfunctionNoAdded in v6.7callback function when upload is aborted
onUploadProgressfunctionNoAdded in v5.1callback function for upload progress
onBeforeUploadBegin(files: File[]) => File[]NoAdded in v6.0callback function called before uploading starts. The files returned are the files that will be uploaded
onUploadBeginfunctionNoAdded in v5.4callback function for upload begin
configConfigNoAdded in v5.7object to pass additional configuration for button
disabledbooleanNoAdded in v6.7Disables the button.

Config object

AttributeTypeRequiredNotesDescription
appendOnPastebooleanNoAdded in v5.7enables 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;
 
  // Matches what's returned from the serverside `onUploadComplete` callback
  // Will be `null` if `skipPolling` is set to `true`.
  serverdata: TServerOutput;
};

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.

app/example-uploader.tsx
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);
    }}
    onDrop={(acceptedFiles) => {
      // Do something with the accepted files
      console.log("Accepted files: ", acceptedFiles);
    }}
  />
);

Configuration

PropTypeRequiredNotesDescription
<FileRouter>genericYesThe type from the FileRouter you defined in your backend
endpointstringYesThe name of the route you want this button to upload to
urlstring | URLNoAdded in v6.0The url to where you are serving your uploadthing file router, required if you're not serving from /api/uploadthing
inputstringIf set on the filerouteAdded in v5.0Object matching the input schema that was set for this endpoint in your File Router
headersHeadersInit | (() => MaybePromise\<HeadersInit\>)NoAdded in v6.4Send custom headers with the API requests to your server. Primarily for authentication when using a separate backend.
skipPollingbooleanNoAdded in v6.3Skip polling for server data. Defaults to true if no onClientUploadComplete is set, else false.
onClientUploadComplete(res: UploadedFileResponse[]) => voidNocallback function that runs after the serverside onUploadComplete callback.
onUploadErrorfunctionNocallback function when upload fails
onUploadAbortedfunctionNoAdded in v6.7callback function when upload is aborted
onUploadProgressfunctionNoAdded in v5.1callback function for upload progress
onBeforeUploadBegin(files: File[]) => File[]NoAdded in v6.0callback function called before uploading starts. The files returned are the files that will be uploaded
onUploadBeginfunctionNoAdded in v5.4callback function for upload begin
configobjectNoAdded in v5.4object to pass additional configuration for dropzone
onDrop(acceptedFiles: File[]) => voidNoAdded in v6.5Callback called when files are dropped or pasted.
disabledbooleanNoAdded in v6.7Disables the dropzone.

Config object

AttributeTypeRequiredNotesDescription
mode'auto' | 'manual'NoAdded in v5.4mode of dropzone. 'manual' is default one. 'auto' triggers upload right after selection
appendOnPastebooleanNoAdded in v5.7enables 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

PropTypeRequiredNotesDescription
urlstring | URLNoAdded in v6.0The 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)

app/example-custom-uploader.tsx
// 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
OptionTypeRequiredNotesDescription
headersHeadersInit | (() => MaybePromise\<HeadersInit\>)NoAdded in v6.4Send custom headers with the API requests to your server. Primarily for authentication when using a separate backend.
skipPollingbooleanNoAdded in v6.3Skip polling for server data.
onClientUploadComplete(res: UploadedFileResponse[]) => voidNocallback function that runs after the serverside onUploadComplete callback.
onUploadErrorfunctionNocallback function when upload fails
onUploadProgressfunctionNoAdded in v5.1callback function for upload progress
onBeforeUploadBegin(files: File[]) => File[]NoAdded in v5.8callback function called before uploading starts. The files returned are the files that will be uploaded
onUploadBeginfunctionNoAdded in v5.4callback function for upload begin
signalAbortSignalNoAdded in v6.7Abort signal to abort the upload

Returns

PropTypeDescription
startUploadfunction(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.
isUploadingfunctionif file(s) are currently uploading
permittedFileInfofunctioninformation 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
})
ArgumentsTypeRequiredNotesDescription
filesFile[]YesThe files you intend to upload
endpointstringYesThe name of the route you want to upload to
inputstringIf set on the filerouteAdded in v5.0Object matching the input schema that was set for this endpoint in your File Router