We are currently working on a new version of the documentation.

useDownload

Generate presigned download URLs and trigger browser downloads or previews.

useDownload requests a presigned download URL from the server and optionally triggers a browser download or opens the file in a new tab.

Basic Usage

components/download.tsx

import { storageClient } from "@/lib/storage-client";

const { useDownload } = storageClient;

function DownloadButton({ fileKey }: { fileKey: string }) {
  const { state, download } = useDownload();

  const handleClick = async () => {
    await download(fileKey, { mode: "direct-download" });
  };

  return (
    <button onClick={handleClick} disabled={state.isLoading}>
      {state.isLoading ? "Preparing…" : "Download"}
    </button>
  );
}

Options

OptionTypeDescription
onSuccess(result: DownloadFileResult) => voidCalled when the download URL is ready
onError(error: StorageError) => voidCalled when the request fails
throwOnErrorbooleanOverride the client-level throwOnError setting

State

FieldTypeDescription
status"idle" | "loading" | "success" | "error"Current request status
isLoadingbooleantrue while requesting the download URL
dataDownloadFileResult | nullResult containing the presigned URL
errorStorageError | nullError details on failure

Methods

MethodSignatureDescription
download(key: string, options?: DownloadOptions) => Promise<DownloadFileResult | undefined>Request a download URL. Returns the result or undefined on error.
reset() => voidReset state back to idle

Download Options

Pass options as the second argument to download():

OptionTypeDefaultDescription
mode"url" | "direct-download" | "preview""url"How to handle the presigned URL
expiresInnumberURL expiration time in seconds
encryptionS3EncryptionEncryption config for SSE-C downloads

Download Modes

"url" (default)

Returns the presigned URL without triggering any browser action. Use this when you want to display the URL or handle the download yourself:

const result = await download("uploads/report.pdf");
console.log(result?.presignedUrl);

"direct-download"

Fetches the file from the presigned URL and triggers a browser download dialog. The filename is extracted from the S3 key:

await download("uploads/report.pdf", { mode: "direct-download" });

"preview"

Opens the file in a new browser tab using window.open():

await download("uploads/image.png", { mode: "preview" });

Download Result

On success, state.data contains:

type DownloadFileResult = {
  presignedUrl: string;
  downloadHeaders?: Record<string, string>;
};

Next Steps