Skip to main content

PG Cloud Storage

Mode

This page documents the PG-mode JS SDK. For classic-mode environments, use the classic version.

CloudBase JS SDK v3 PG mode provides PostgreSQL-native bucket-based cloud storage capabilities. Use app.storage.from(bucketId) to get the object client for a specific bucket. All path parameters are object names inside the bucket; do not pass cloud:// fileIDs.

Quick Start​

import cloudbase from "@cloudbase/js-sdk";

const app = cloudbase.init({ env: "your-env-id" });
const bucket = app.storage.from("avatars");

const { data, error } = await bucket.upload("user-123/avatar.png", file, {
contentType: "image/png",
upsert: true,
});
if (error) throw error;

const { data: blob } = await bucket.download("user-123/avatar.png");
const { data: signed } = await bucket.createSignedUrl("user-123/avatar.png", 3600);
await bucket.remove(["user-123/avatar.png"]);

API Methods​

Bucket Client​

File Operations​

URL Management​

File Information​

  • info() - Get file information
  • exists() - Check whether a file exists

Bucket Management​


from​

from(bucketId: string): PostgresNativeStorageFileApi

type PostgresNativeStorageFileApi = StorageFileApi;

Parameters

bucketId
string

PG Bucket ID, corresponding to `storage.buckets.id`.

Response

PostgresNativeStorageFileApi
Object

Native PG bucket object operation client.

Example

const bucket = app.storage.from("avatars");

throwOnError​

throwOnError(): this

Parameters

No parameters

Response

this
PostgresNativeStorageFileApi

Current client instance for chaining.

Example

const bucket = app.storage.from("avatars").throwOnError();
await bucket.upload("user-123/avatar.png", file);

upload​

Upload a file to storage.

A single upload is limited to 200 MB. The limit uses the byte length when it is known. Streams of unknown length are not checked locally. Use uploadResumable() for larger files.

upload(path: string, fileBody: FileBody, fileOptions?: UploadOptions): Promise<Result<UploadResult>>

type FileBody = File | Blob | ArrayBuffer | ArrayBufferView | FormData | ReadableStream<Uint8Array> | string;

type Result<T> = { data: T; error: null } | { data: null; error: StorageError };

interface UploadOptions {
cacheControl?: string;
contentType?: string;
metadata?: Record<string, any>;
upsert?: boolean; // default false
}

interface UploadResult {
id: string;
path: string;
fullPath: string; // bucketId/objectName
}

Parameters

path
string

Object name inside the bucket, for example `user-123/avatar.png`. Do not pass `cloud://` fileIDs.

fileBody
FileBody

File content. A single upload is limited to 200 MB. Streams of unknown length are not checked against this limit.

fileOptions
UploadOptions

Upload options. Pass `upsert: true` to overwrite existing objects.

Response

data
Object

Return data

error
StorageError | null

Error.

Example

const { data, error } = await app.storage.from("avatars").upload("user-123/avatar.png", file, {
contentType: "image/png",
upsert: true,
metadata: { usage: "avatar" },
});

if (error) throw error;
console.log(data.fullPath);

uploadResumable​

Note

TUS resumable upload is in Public Beta and no SLA is provided. Evaluate it before using it in production.

Resumable upload. Requires @cloudbase/js-sdk 3.11.1 or later.

The return value can be awaited, and it also has abort(terminate?). The awaited result does not include an object UUID. upload() stays a single request, limited to 200 MB. The same limit applies to update() and uploadToSignedUrl(). Use this method for larger files.

uploadResumable(
path: string,
fileBody: FileBody,
options?: ResumableUploadOptions
): ResumableUpload

interface ResumableUpload extends PromiseLike<Result<ResumableUploadResult>> {
abort(terminate?: boolean): Promise<void>;
}

interface ResumableUploadOptions {
cacheControl?: string; // default "3600", in seconds
contentType?: string;
upsert?: boolean;
metadata?: Record<string, any>;
headers?: Record<string, string>;
token?: string;
chunkSize?: number;
retryDelays?: number[];
onProgress?: (bytesUploaded: number, bytesTotal: number) => void;
signal?: AbortSignal;
urlStorage?: TusUrlStorage;
}

interface ResumableUploadResult {
path: string;
fullPath: string; // bucketId/objectName
uploadUrl: string | null;
size: number;
}

Parameters

path
string

Object name inside the bucket. Do not pass a `cloud://` fileID.

fileBody
FileBody

File content with a known byte length. When the adapter provides a file class, a string is a local path.

options
ResumableUploadOptions

Resumable upload options.

Response

data
Object

Return data

error
StorageError | null

Error.

Example

const bucket = app.storage.from("avatars");
const task = bucket.uploadResumable("user-123/video.mp4", file, {
contentType: file.type,
upsert: true,
onProgress: (loaded, total) => {
console.log(loaded, total);
},
});

const { data, error } = await task;
if (error) throw error;
console.log(data.fullPath, data.size);

// Cancel and tell the server to terminate the session
// await task.abort(true);

fileBody must have a known byte length. Supported inputs are File, Blob, Buffer, ArrayBuffer, binary views, UTF-8 strings, and FormData that contains exactly one file. A stream of unknown length cannot be resumed.

When the adapter provides a file class, a string is a local path. WeChat Mini Programs and uni-app are in this group. In the browser and in Node.js, a string is still UTF-8 content.

A file cannot exceed 100 GiB or 10000 chunks. The SDK rejects an over-limit upload and does not create a session.

When chunkSize is omitted, the SDK picks a chunk from the file size and then limits it to 1 MB–60 MB:

File sizeChunk
Under 30 MB6 MB
Under 100 MBfile size / 8
Under 500 MBfile size / 10
Under 1 GBfile size / 20
Under 10 GBfile size / 30
Otherwisefile size / 50

If that chunk would produce more than 10000 parts, the SDK raises the chunk size, still not above 60 MB. An explicit chunkSize is also limited to 1 MB–60 MB. Local-path uploads are capped at 4 MB per chunk. If 4 MB chunks would still exceed 10000 chunks, the upload is rejected.

Each local-path request times out after 60 seconds. It does not use the 15-second default from init.

The session URL is stored in this order:

  • urlStorage, when the caller passes one
  • Adapter storage that implements keys(). A cold start can then resume
  • Browser localStorage. A refresh can then resume
  • The current process on Node.js and the CLI. The session is lost when the process exits

The request sends the login header by default. With token, it uses /upload/resumable/sign and sends x-signature instead of a login header. token comes from createSignedUploadUrl().

abort(true) sends DELETE and terminates the server session. Terminating an upload that already finished gets HTTP 405. abort() and signal stop the client only and do not send DELETE.

409, 423, 5xx, and network errors retry on retryDelays. Other 4xx responses do not retry. A PATCH response of 410 or 404 clears the stored session. The next call creates a new session.


update​

Update an existing file. The size limit matches upload(): a single upload is limited to 200 MB.

update(path: string, fileBody: FileBody, fileOptions?: UploadOptions): Promise<Result<UploadResult>>

interface UploadOptions {
cacheControl?: string;
contentType?: string;
metadata?: Record<string, any>;
}

Parameters

path
string

Object name inside the bucket.

fileBody
FileBody

New file content.

fileOptions
UploadOptions

Upload options.

Response

data
UploadResult | null

Update result.

error
StorageError | null

Error.

Example

await app.storage.from("avatars").update("user-123/avatar.png", newFile, {
contentType: "image/png",
});

download​

Download a file.

download(path: string, options?: DownloadOptions, parameters?: FetchParameters): DownloadBuilder

interface DownloadOptions {
download?: string | boolean;
cacheNonce?: string;
}

interface FetchParameters {
signal?: AbortSignal;
cache?: RequestCache;
}

Parameters

path
string

Object name inside the bucket.

options
DownloadOptions

Download options.

parameters
FetchParameters

Request control parameters.

Response

data
Blob | ReadableStream | null

Await returns Blob by default. `.asStream()` returns ReadableStream.

error
StorageError | null

Error.

Example

const { data: blob } = await app.storage.from("avatars").download("user-123/avatar.png");

const { data: stream } = await app.storage
.from("videos")
.download("demo.mp4")
.asStream();

remove​

Delete one or more files.

remove(paths: string[]): Promise<Result<FullObject[]>>

interface FullObject {
name: string;
bucket_id: string;
owner_id?: string | null;
metadata?: Record<string, any>;
}

Parameters

paths
string[]

Object names inside the bucket.

Response

data
FullObject[] | null

Deleted object information.

error
StorageError | null

Error.

Example

await app.storage.from("avatars").remove(["user-123/avatar.png"]);

move​

Move a file to a new path.

move(fromPath: string, toPath: string, options?: DestinationOptions): Promise<Result<{ message: string }>>

interface DestinationOptions {
destinationBucket?: string;
upsert?: boolean;
}

Parameters

fromPath
string

Source object name.

toPath
string

Destination object name.

options
DestinationOptions

Destination bucket options.

Response

data
Object

Return data

error
StorageError | null

Error.

Example

await app.storage.from("avatars").move("user-123/avatar.png", "user-123/archive/avatar.png");

copy​

Copy a file to a new path.

copy(fromPath: string, toPath: string, options?: DestinationOptions): Promise<Result<{ path: string }>>

interface DestinationOptions {
destinationBucket?: string;
upsert?: boolean;
copyMetadata?: boolean;
metadata?: Record<string, any>;
}

Parameters

fromPath
string

Source object name.

toPath
string

Destination object name.

options
DestinationOptions

Cross-bucket and metadata options.

Response

data
Object

Return data

error
StorageError | null

Error.

Example

await app.storage.from("avatars").copy("user-123/avatar.png", "user-123/avatar-copy.png", {
upsert: true,
copyMetadata: true,
});

createSignedUrl​

Create a temporary access URL.

createSignedUrl(path: string, expiresIn: number, options?: SignedUrlOptions): Promise<Result<SignedUrlResult>>

interface SignedUrlOptions {
download?: string | boolean;
cacheNonce?: string;
}

interface SignedUrlResult {
fullSignedURL: string;
}

Parameters

path
string

Object name inside the bucket.

expiresIn
number

Expiration in seconds.

options
SignedUrlOptions

Signed URL options.

Response

data
Object

Return data

error
StorageError | null

Error.

Example

const { data } = await app.storage.from("avatars").createSignedUrl("user-123/avatar.png", 3600, {
download: "avatar.png",
});

createSignedUrls​

Create temporary access URLs in batch.

createSignedUrls(paths: string[], expiresIn: number, options?: SignedUrlOptions): Promise<Result<SignedUrlsResultItem[]>>

interface SignedUrlsResultItem {
path: string;
fullSignedURL: string | null;
error: string | null;
}

Parameters

paths
string[]

Object names inside the bucket.

expiresIn
number

Expiration in seconds.

options
SignedUrlOptions

Signed URL options.

Response

data
SignedUrlsResultItem[] | null

Batch signing results.

error
StorageError | null

Error.

Example

await app.storage.from("avatars").createSignedUrls(["user-123/avatar.png"], 3600);

getPublicUrl​

Get a public access URL.

getPublicUrl(path: string, options?: PublicUrlOptions): { data: { publicUrl: string } }

interface PublicUrlOptions {
download?: string | boolean;
cacheNonce?: string;
}

Parameters

path
string

Object name inside the bucket.

options
PublicUrlOptions

Public URL options.

Response

data
Object

Return data

Example

const { data } = app.storage.from("public-assets").getPublicUrl("logos/cloudbase.png");

info​

Get file information.

info(path: string): Promise<Result<ObjectInfo>>

interface ObjectInfo {
id: string;
name: string;
bucketId: string;
size?: number | null;
contentType?: string | null;
metadata?: Record<string, any>;
createdAt?: string | null;
}

Parameters

path
string

Object name inside the bucket.

Response

data
ObjectInfo | null

Object metadata.

error
StorageError | null

Error.

Example

await app.storage.from("avatars").info("user-123/avatar.png");

exists​

Check whether a file exists.

exists(path: string): Promise<Result<boolean>>

Parameters

path
string

Object name inside the bucket.

Response

data
boolean | null

Whether it exists.

error
StorageError | null

Error.

Example

await app.storage.from("avatars").exists("user-123/avatar.png");

createSignedUploadUrl​

Create a signed upload URL.

createSignedUploadUrl(path: string, options?: { upsert?: boolean }): Promise<Result<CreateSignedUploadUrlResult>>

interface CreateSignedUploadUrlResult {
fullSignedURL: string;
token: string;
path: string;
}

Parameters

path
string

Object name inside the bucket.

options
{ upsert?: boolean }

Whether to allow overwrite.

Response

data
CreateSignedUploadUrlResult | null

Signed upload URL and token.

error
StorageError | null

Error.

Example

const bucket = app.storage.from("avatars");
const { data: signed } = await bucket.createSignedUploadUrl("user-123/avatar.png", { upsert: true });
await bucket.uploadToSignedUrl("user-123/avatar.png", signed.token, file);

uploadToSignedUrl() uses the same size limit as upload(): a single upload is limited to 200 MB.


list​

List objects in a bucket.

list(path?: string, options?: ListOptions, parameters?: FetchParameters): Promise<Result<ListObjectsResponse>>

interface ListOptions {
limit?: number;
cursor?: string;
withDelimiter?: boolean;
sortBy?: { column?: "name" | "created_at" | "updated_at"; order?: "asc" | "desc" };
}

Parameters

path
string

Prefix. Omit it to list the bucket root.

options
ListOptions

List options.

Response

data
ListObjectsResponse | null

Contains folders, objects, hasNext, and nextCursor.

error
StorageError | null

Error.

Example

const { data } = await app.storage.from("avatars").list("user-123", {
limit: 20,
withDelimiter: true,
});

Bucket management​

The following APIs are mounted directly on app.storage and are only available in PG mode:

listBuckets(options?: ListBucketOptions): Promise<Result<Bucket[]>>
getBucket(bucketId: string): Promise<Result<Bucket>>
createBucket(bucketId: string, options?: CreateBucketOptions): Promise<Result<{ name: string }>>
updateBucket(bucketId: string, options: UpdateBucketOptions): Promise<Result<{ message: string }>>
deleteBucket(bucketId: string): Promise<Result<{ message: string }>>

interface CreateBucketOptions {
public?: boolean;
type?: "STANDARD";
fileSizeLimit?: number | string | null;
allowedMimeTypes?: string[] | null;
}

Parameters

bucketId
string

Bucket ID.

options
Object

Bucket configuration.

Response

data
Bucket | Bucket[] | Object | null

Bucket operation result.

Example

await app.storage.createBucket("avatars", {
public: false,
type: "STANDARD",
fileSizeLimit: "100MB",
allowedMimeTypes: ["image/png", "image/jpeg"],
});

const { data: buckets } = await app.storage.listBuckets({ limit: 20, offset: 0 });


Best Practices

1. Error handling​

const { data, error } = await app.storage.from("avatars").upload("user-123/avatar.png", file);

if (error) {
console.error("Operation failed:", error.message);
return;
}

2. Path rules​

  • Select a bucket with from(bucketId) first. All subsequent paths are object names inside that bucket.
  • Do not pass cloud:// fileIDs.
  • Do not start paths with / or include consecutive /.

FAQ

1. Why should I not pass cloud:// fileIDs in PG mode?​

The native PG API already selects the bucket through from(bucketId). Method path arguments are object names inside that bucket.

2. Where are file permissions configured?​

PG mode is controlled by RLS policies on storage.objects / storage.buckets.

Related Resources