Skip to content

Storage

This is the main module to interact with Nhost’s Storage service. Typically you would use this module via the main Nhost client but you can also use it directly if you have a specific use case.

You can import and use this package with:

import { createClient } from '@nhost/nhost-js/storage'

You can use this library to upload files, download files, and delete files:

import { createClient } from '@nhost/nhost-js'
const nhost = createClient({
subdomain,
region
})
// Sign up/in to authenticate
await nhost.auth.signUpEmailPassword({
email: `test-${Date.now()}@example.com`,
password: 'password123'
})
// Upload files to storage
const uploadResp = await nhost.storage.uploadFiles({
'file[]': [new File(['test content'], 'test-file.txt', { type: 'text/plain' })]
})
console.log(JSON.stringify(uploadResp, null, 2))
// {
// "body": {
// "processedFiles": [
// {
// "id": "412f4ec0-e347-4e1e-ad5a-8fecb6cb51ed",
// "name": "test-file.txt",
// "size": 12,
// "bucketId": "default",
// "etag": "\"9473fdd0d880a43c21b7778d34872157\"",
// "createdAt": "2025-07-04T08:27:26.018321+00:00",
// "updatedAt": "2025-07-04T08:27:26.021849+00:00",
// "isUploaded": true,
// "mimeType": "text/plain",
// "uploadedByUserId": "",
// "metadata": null
// }
// ]
// },
// "status": 201,
// "headers": {}
// }
const fileId = uploadResp.body.processedFiles[0].id
// Download a file from storage
const downloadResp = await nhost.storage.getFile(fileId)
console.log('Downloaded file content:', await downloadResp.body.text())
// Downloaded file content: test content
// Delete the file
await nhost.storage.deleteFile(fileId)

The SDK will throw errors in most operations if the request returns a status >=300 or if the request fails entirely (i.e., due to network errors). The type of the error will be a FetchError<ErrorResponse>:

import { createClient } from '@nhost/nhost-js'
import type { FetchError } from '@nhost/nhost-js/fetch'
import type { ErrorResponse } from '@nhost/nhost-js/storage'
const nhost = createClient({
subdomain,
region
})
try {
await nhost.storage.uploadFiles({
'file[]': [new File(['test1'], 'file-1', { type: 'text/plain' })]
})
} catch (error) {
const err = error as FetchError<ErrorResponse>
console.log('Error:', err)
// Error: {
// body: { error: { message: 'you are not authorized' } },
// status: 403,
// headers: {
// 'content-length': '46',
// 'content-type': 'application/json; charset=utf-8',
// date: 'Mon, 12 May 2025 08:18:52 GMT'
// }
// }
// error handling...
}

This type extends the standard Error type so if you want to just log the error you can do so like this:

import { createClient } from '@nhost/nhost-js'
import type { FetchError } from '@nhost/nhost-js/fetch'
import type { ErrorResponse } from '@nhost/nhost-js/storage'
const nhost = createClient({
subdomain,
region
})
try {
await nhost.storage.uploadFiles({
'file[]': [new File(['test1'], 'file-1', { type: 'text/plain' })]
})
} catch (error) {
if (!(error instanceof Error)) {
throw error // Re-throw if it's not an Error
}
console.log('Error:', error.message)
// Error: you are not authorized
// error handling...
}
baseURL: string
deleteBrokenMetadata(options?: RequestInit): Promise<FetchResponse<DeleteBrokenMetadataResponse200>>;

Summary: Delete broken metadata Broken metadata is defined as metadata that has isUploaded = true but there is no file in the storage matching it. This is an admin operation that requires the Hasura admin secret.

This method may return different T based on the response code:

  • 200: DeleteBrokenMetadataResponse200
ParameterType
options?RequestInit

Promise<FetchResponse<DeleteBrokenMetadataResponse200>>

deleteFile(id: string, options?: RequestInit): Promise<FetchResponse<void>>;

Summary: Delete file Permanently delete a file from storage. This removes both the file content and its associated metadata.

This method may return different T based on the response code:

  • 204: void
ParameterType
idstring
options?RequestInit

Promise<FetchResponse<void>>

deleteOrphanedFiles(options?: RequestInit): Promise<FetchResponse<DeleteOrphanedFilesResponse200>>;

Summary: Deletes orphaned files Orphaned files are files that are present in the storage but have no associated metadata. This is an admin operation that requires the Hasura admin secret.

This method may return different T based on the response code:

  • 200: DeleteOrphanedFilesResponse200
ParameterType
options?RequestInit

Promise<FetchResponse<DeleteOrphanedFilesResponse200>>

getFile(
id: string,
params?: GetFileParams,
options?: RequestInit): Promise<FetchResponse<Blob>>;

Summary: Download file Retrieve and download the complete file content. Supports conditional requests, image transformations, and range requests for partial downloads.

This method may return different T based on the response code:

  • 200: void
  • 206: void
  • 304: void
  • 412: void
ParameterType
idstring
params?GetFileParams
options?RequestInit

Promise<FetchResponse<Blob>>

getFileMetadataHeaders(
id: string,
params?: GetFileMetadataHeadersParams,
options?: RequestInit): Promise<FetchResponse<void>>;

Summary: Check file information Retrieve file metadata headers without downloading the file content. Supports conditional requests and provides caching information.

This method may return different T based on the response code:

  • 200: void
  • 304: void
  • 412: void
ParameterType
idstring
params?GetFileMetadataHeadersParams
options?RequestInit

Promise<FetchResponse<void>>

getFilePresignedURL(id: string, options?: RequestInit): Promise<FetchResponse<PresignedURLResponse>>;

Summary: Retrieve presigned URL to retrieve the file Retrieve presigned URL to retrieve the file. Expiration of the URL is determined by bucket configuration

This method may return different T based on the response code:

  • 200: PresignedURLResponse
ParameterType
idstring
options?RequestInit

Promise<FetchResponse<PresignedURLResponse>>

getVersion(options?: RequestInit): Promise<FetchResponse<VersionInformation>>;

Summary: Get service version information Retrieves build and version information about the storage service. Useful for monitoring and debugging.

This method may return different T based on the response code:

  • 200: VersionInformation
ParameterType
options?RequestInit

Promise<FetchResponse<VersionInformation>>

listBrokenMetadata(options?: RequestInit): Promise<FetchResponse<ListBrokenMetadataResponse200>>;

Summary: Lists broken metadata Broken metadata is defined as metadata that has isUploaded = true but there is no file in the storage matching it. This is an admin operation that requires the Hasura admin secret.

This method may return different T based on the response code:

  • 200: ListBrokenMetadataResponse200
ParameterType
options?RequestInit

Promise<FetchResponse<ListBrokenMetadataResponse200>>

listFilesNotUploaded(options?: RequestInit): Promise<FetchResponse<ListFilesNotUploadedResponse200>>;

Summary: Lists files that haven’t been uploaded That is, metadata that has isUploaded = false. This is an admin operation that requires the Hasura admin secret.

This method may return different T based on the response code:

  • 200: ListFilesNotUploadedResponse200
ParameterType
options?RequestInit

Promise<FetchResponse<ListFilesNotUploadedResponse200>>

listOrphanedFiles(options?: RequestInit): Promise<FetchResponse<ListOrphanedFilesResponse200>>;

Summary: Lists orphaned files Orphaned files are files that are present in the storage but have no associated metadata. This is an admin operation that requires the Hasura admin secret.

This method may return different T based on the response code:

  • 200: ListOrphanedFilesResponse200
ParameterType
options?RequestInit

Promise<FetchResponse<ListOrphanedFilesResponse200>>

pushChainFunction(chainFunction: ChainFunction): void;

Add a middleware function to the fetch chain

ParameterTypeDescription
chainFunctionChainFunctionThe middleware function to add

void

replaceFile(
id: string,
body: ReplaceFileBody,
options?: RequestInit): Promise<FetchResponse<FileMetadata>>;

Summary: Replace file Replace an existing file with new content while preserving the file ID. The operation follows these steps:

  1. The isUploaded flag is set to false to mark the file as being updated
  2. The file content is replaced in the storage backend
  3. File metadata is updated (size, mime-type, isUploaded, etc.)

Each step is atomic, but if a step fails, previous steps will not be automatically rolled back.

This method may return different T based on the response code:

  • 200: FileMetadata
ParameterType
idstring
bodyReplaceFileBody
options?RequestInit

Promise<FetchResponse<FileMetadata>>

uploadFiles(body: UploadFilesBody, options?: RequestInit): Promise<FetchResponse<UploadFilesResponse201>>;

Summary: Upload files Upload one or more files to a specified bucket. Supports batch uploading with optional custom metadata for each file. If uploading multiple files, either provide metadata for all files or none.

This method may return different T based on the response code:

  • 201: UploadFilesResponse201
ParameterType
bodyUploadFilesBody
options?RequestInit

Promise<FetchResponse<UploadFilesResponse201>>


optional metadata: FileSummary[];

optional files: string[];

Error information returned by the API.

optional error: ErrorResponseError;

Error details.


Error details.

optional data: Record<string, unknown>;

Additional data related to the error, if any.

message: string

(string) - Human-readable error message.

  • Example - "File not found"

Error information returned by the API.

optional error: ErrorResponseWithProcessedFilesError;

Error details.

optional processedFiles: FileMetadata[];

List of files that were successfully processed before the error occurred.


Error details.

optional data: Record<string, unknown>;

Additional data related to the error, if any.

message: string

(string) - Human-readable error message.

  • Example - "File not found"

Comprehensive metadata information about a file in storage.

bucketId: string

(string) - ID of the bucket containing the file.

  • Example - "users-bucket"
createdAt: string

(string) - Timestamp when the file was created.

  • Example - "2023-01-15T12:34:56Z"
  • Format - date-time
etag: string

(string) - Entity tag for cache validation.

  • Example - "\"a1b2c3d4e5f6\""
id: string

(string) - Unique identifier for the file.

  • Example - "d5e76ceb-77a2-4153-b7da-1f7c115b2ff2"
isUploaded: boolean

(boolean) - Whether the file has been successfully uploaded.

  • Example - true
optional metadata: Record<string, unknown>;

Custom metadata associated with the file. Example - {"alt":"Profile picture","category":"avatar"}

mimeType: string

(string) - MIME type of the file.

  • Example - "image/jpeg"
name: string

(string) - Name of the file including extension.

  • Example - "profile-picture.jpg"
size: number

(number) - Size of the file in bytes.

  • Example - 245678
  • Format - int64
updatedAt: string

(string) - Timestamp when the file was last updated.

  • Example - "2023-01-16T09:45:32Z"
  • Format - date-time
optional uploadedByUserId: string;

ID of the user who uploaded the file. Example - "abc123def456"


Basic information about a file in storage.

bucketId: string

(string) - ID of the bucket containing the file.

  • Example - "users-bucket"
id: string

(string) - Unique identifier for the file.

  • Example - "d5e76ceb-77a2-4153-b7da-1f7c115b2ff2"
isUploaded: boolean

(boolean) - Whether the file has been successfully uploaded.

  • Example - true
name: string

(string) - Name of the file including extension.

  • Example - "profile-picture.jpg"

Parameters for the getFileMetadataHeaders method.

optional b: number;

Blur the image using this sigma value. Only applies to image files

optional f: OutputImageFormat;

Output format for image files. Use ‘auto’ for content negotiation based on Accept header

  • Output format for image files. Use ‘auto’ for content negotiation based on Accept header
optional h: number;

Maximum height to resize image to while maintaining aspect ratio. Only applies to image files

optional q: number;

Image quality (1-100). Only applies to JPEG, WebP, PNG and HEIC files

optional w: number;

Maximum width to resize image to while maintaining aspect ratio. Only applies to image files


Parameters for the getFile method.

optional b: number;

Blur the image using this sigma value. Only applies to image files

optional f: OutputImageFormat;

Output format for image files. Use ‘auto’ for content negotiation based on Accept header

  • Output format for image files. Use ‘auto’ for content negotiation based on Accept header
optional h: number;

Maximum height to resize image to while maintaining aspect ratio. Only applies to image files

optional q: number;

Image quality (1-100). Only applies to JPEG, WebP, PNG and HEIC files

optional w: number;

Maximum width to resize image to while maintaining aspect ratio. Only applies to image files


optional metadata: FileSummary[];

optional metadata: FileSummary[];

optional files: string[];

Contains a presigned URL for direct file operations.

expiration: number

(number) - The time in seconds until the URL expires.

  • Example - 3600
url: string

(string) - The presigned URL for file operations.

  • Example - "https://storage.example.com/files/abc123?signature=xyz"

optional file: Blob;

New file content to replace the existing file Format - binary

optional metadata: UpdateFileMetadata;

Metadata that can be updated for an existing file.


Metadata that can be updated for an existing file.

optional metadata: Record<string, unknown>;

Updated custom metadata to associate with the file. Example - {"alt":"Updated image description","category":"profile"}

optional name: string;

New name to assign to the file. Example - "renamed-file.jpg"


Metadata provided when uploading a new file.

optional id: string;

Optional custom ID for the file. If not provided, a UUID will be generated. Example - "custom-id-123"

optional metadata: Record<string, unknown>;

Custom metadata to associate with the file. Example - {"alt":"Custom image","category":"document"}

optional name: string;

Name to assign to the file. If not provided, the original filename will be used. Example - "custom-filename.png"


optional bucket-id: string;

Target bucket identifier where files will be stored. Example - "user-uploads"

file[]: Blob[];

(Blob[]) - Array of files to upload.

optional metadata[]: UploadFileMetadata[];

Optional custom metadata for each uploaded file. Must match the order of the file[] array.


processedFiles: FileMetadata[];

(FileMetadata[]) - List of successfully processed files with their metadata.


Contains version information about the storage service.

buildVersion: string

(string) - The version number of the storage service build.

  • Example - "1.2.3"
type OutputImageFormat = 'auto' | 'same' | 'jpeg' | 'webp' | 'png' | 'avif' | 'heic'

Output format for image files. Use ‘auto’ for content negotiation based on Accept header


type RFC2822Date = string

Date in RFC 2822 format

function createAPIClient(baseURL: string, chainFunctions: ChainFunction[]): Client
ParameterTypeDefault value
baseURLstringundefined
chainFunctionsChainFunction[][]

Client