Storage Queries
The Supabase Cache Helpers provide optimized query hooks for interacting with Supabase Storage using React Query or SWR. These hooks streamline caching, signed URL generation, and storage operations.
Query Configuration Options
Most query hooks accept a configuration object based on React Query’s UseQueryOptions
or SWR’s equivalent.
// Base type for query configuration
type QueryConfig<TData> = Omit<UseQueryOptions<TData | undefined, StorageError>, 'queryKey' | 'queryFn'>;
Common Options
These options are commonly used across all query hooks:
Option | Type | Description |
---|---|---|
refetchOnWindowFocus | boolean | Refetches data when the window regains focus. Defaults to true . |
staleTime | number | Time in milliseconds before data is considered stale. |
cacheTime | number | Time in milliseconds to cache data before garbage collection. |
enabled | boolean | If false , disables the query from automatically running. |
onSuccess | (data: TData) => void | Callback when the query successfully fetches data. |
onError | (error: StorageError) => void | Callback when the query encounters an error. |
For the full list of React Query options, see the React Query useQuery
documentation.
Additional Options for useDirectoryFileUrls
In addition to the common options, useDirectoryFileUrls
includes:
// Extended configuration for useDirectoryFileUrls
type DirectoryFileUrlsConfig = Omit<UseQueryOptions<(FileObject & { url: string })[] | undefined, StorageError>, 'queryKey' | 'queryFn'> &
Pick<URLFetcherConfig, 'expiresIn'>;
Option | Type | Description |
---|---|---|
expiresIn | number | Number of seconds before a signed URL expires (only for private storage). |
Each hook’s documentation specifies which options apply.
Fetching File URLs
useFileUrl
Fetches the URL of a file in Supabase Storage, handling both private and public files.
Parameters:
useFileUrl(
fileApi: StorageFileApi, // Supabase storage API instance
path: string, // Path to the file (e.g., 'dirname/myfile.jpg')
mode: 'public' | 'private', // Storage privacy mode
config?: URLFetcherConfig // Optional fetcher config (see below)
)
URLFetcherConfig
Options:
type URLFetcherConfig = {
expiresIn?: number; // Expiration time for signed URLs (private buckets)
ensureExistence?: boolean; // Check if the file exists (public buckets only)
download?: string | boolean | undefined; // Trigger file download
transform?: TransformOptions | undefined; // Transform image before serving
};
Return Type:
UseQueryResult<string | undefined, StorageError>
Property | Type | Description |
---|---|---|
data | string | undefined | The file URL if found, otherwise undefined . |
error | StorageError | null | Error details if the request fails. |
Usage Example:
import { useFileUrl } from '@supabase-cache-helpers/storage-swr';
import { createClient } from '@supabase/supabase-js';
const client = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_ANON_KEY);
function Page() {
const { data: url } = useFileUrl(
client.storage.from('public_contact_files'),
'dirname/myfile.jpg',
'public',
{ ensureExistence: true, revalidateOnFocus: false }
);
return <div>{url}</div>;
}
Fetching Directory Listings
useDirectory
Fetches all files in a given directory from Supabase Storage.
Parameters:
useDirectory(
fileApi: StorageFileApi, // Supabase storage API instance
path: string, // Directory path (e.g., 'dirname/')
config?: UseQueryOptions<FileObject[] | undefined, StorageError> // Optional query config
)
Return Type:
UseQueryResult<FileObject[] | undefined, StorageError>
Property | Type | Description |
---|---|---|
data | FileObject[] | undefined | List of files in the directory (or undefined if none exist). |
error | StorageError | null | Error details if the request fails. |
FileObject Structure:
type FileObject = {
name: string; // File name (e.g., 'image.png')
id: string; // Unique identifier
updated_at: string; // Last modified timestamp
created_at: string; // Creation timestamp
metadata: Record<string, any>; // File metadata (e.g., size, type)
bucket_id: string; // The storage bucket name
};
Fetching Directory Files with URLs
useDirectoryFileUrls
Fetches all files in a directory and their URLs, combining useDirectory
with useFileUrl
.
Parameters:
useDirectoryFileUrls(
fileApi: StorageFileApi, // Supabase storage API instance
path: string, // Directory path (e.g., 'dirname/')
mode: 'public' | 'private', // Storage privacy mode
config?: UseQueryOptions<(FileObject & { url: string })[] | undefined, StorageError> // Query config
)
Return Type:
UseQueryResult<(FileObject & { url: string })[] | undefined, StorageError>
Property | Type | Description |
---|---|---|
data | (FileObject & { url: string })[] | undefined | List of files with their URLs (or undefined if no files exist). |
error | StorageError | null | Error details if the request fails. |
FileObjectWithUrl Structure:
type FileObjectWithUrl = FileObject & {
url: string; // The signed or public URL for the file
};