StorageQueries

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:

OptionTypeDescription
refetchOnWindowFocusbooleanRefetches data when the window regains focus. Defaults to true.
staleTimenumberTime in milliseconds before data is considered stale.
cacheTimenumberTime in milliseconds to cache data before garbage collection.
enabledbooleanIf false, disables the query from automatically running.
onSuccess(data: TData) => voidCallback when the query successfully fetches data.
onError(error: StorageError) => voidCallback 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'>;
OptionTypeDescription
expiresInnumberNumber 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>
PropertyTypeDescription
datastring | undefinedThe file URL if found, otherwise undefined.
errorStorageError | nullError 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>
PropertyTypeDescription
dataFileObject[] | undefinedList of files in the directory (or undefined if none exist).
errorStorageError | nullError 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>
PropertyTypeDescription
data(FileObject & { url: string })[] | undefinedList of files with their URLs (or undefined if no files exist).
errorStorageError | nullError details if the request fails.

FileObjectWithUrl Structure:

type FileObjectWithUrl = FileObject & {
  url: string; // The signed or public URL for the file
};