Hooks
useFileDownload
A React hook that downloads private files by fetching a signed URL from your API, then streaming the file as a blob to trigger a browser download with a controlled filename. Includes abort support, loading state, and error handling.
Installation
bunx @happlyui/cli@latest add use-file-download
Usage
import { useFileDownload } from "@/hooks/use-file-download"
const { download, isDownloading } = useFileDownload({
endpoint: '/api/assets/url',
headers: () => ({ Authorization: `Bearer ${token}` }),
})
Examples
Download Button
Trigger a file download from a button click using a storage key.
import { useFileDownload } from "@/hooks/use-file-download"
function DownloadButton({ fileKey, fileName }: { fileKey: string; fileName: string }) {
const { download, isDownloading, error } = useFileDownload({
endpoint: '/api/assets/url',
headers: () => ({ Authorization: `Bearer ${token}` }),
})
return (
<>
<button onClick={() => download(fileKey, fileName)} disabled={isDownloading}>
{isDownloading ? 'Downloading…' : 'Download'}
</button>
{error && <p className="text-error-base text-sm">{error.message}</p>}
</>
)
}
File List with Active Key Tracking
Show which file is currently downloading in a list using activeKey.
import { useFileDownload } from "@/hooks/use-file-download"
function FileList({ files }: { files: { key: string; name: string }[] }) {
const { download, isDownloading, activeKey } = useFileDownload({
endpoint: '/api/assets/url',
baseUrl: process.env.NEXT_PUBLIC_API_URL,
headers: () => ({
Authorization: `Bearer ${token}`,
'X-Workspace-Id': workspaceId,
}),
})
return (
<ul>
{files.map((file) => (
<li key={file.key} className="flex items-center gap-2">
<span>{file.name}</span>
<button
onClick={() => download(file.key, file.name)}
disabled={isDownloading}
>
{activeKey === file.key ? 'Downloading…' : 'Download'}
</button>
</li>
))}
</ul>
)
}
API Reference
useFileDownload Options
Configuration options passed to the hook.
| Prop | Type | Default | Description |
|---|---|---|---|
endpoint | string | - | API endpoint path that accepts POST { key } and returns { data: { url } } with a signed download URL. |
baseUrl | string | '' | Base URL prepended to the endpoint. |
headers | () => Record<string, string> | - | Function returning headers for the signed-URL request (e.g. auth tokens, workspace keys). Called on each download. |
useFileDownload Return Value
The object returned by the hook.
| Prop | Type | Default | Description |
|---|---|---|---|
download | (key: string, fileName?: string) => Promise<void> | - | Initiate a download for the given storage key. Optionally specify the filename for the saved file. |
isDownloading | boolean | - | True while a download is in progress. |
activeKey | string | null | - | The storage key currently being downloaded, or null when idle. Useful for showing per-item loading states in a list. |
error | Error | null | - | The last download error, or null. Reset on each new download call. |