Drivers

Cloudinary Driver

Upload files to Cloudinary media CDN

Uploads files to Cloudinary using pure fetch, FormData, and Web Crypto signatures. Zero Node dependencies, so it works on any runtime.

import { FilewayClient } from "@fileway/core";
import { CloudinaryDriver } from "@fileway/cloudinary";

const client = new FilewayClient({
  driver: new CloudinaryDriver({
    cloudName: "my-cloud",
    apiKey: process.env.CLOUDINARY_API_KEY!,
    apiSecret: process.env.CLOUDINARY_API_SECRET!,
  }),
});

const result = await client.upload(stream, {
  filename: "avatar.png",
  path: "users/profiles",
});

console.log(result.meta.publicId);
console.log(result.meta.secureUrl);
console.log(result.meta.width, result.meta.height);

Config

OptionTypeDefaultDescription
cloudNamestringRequiredCloudinary cloud name
apiKeystringRequiredCloudinary API key
apiSecretstringRequiredCloudinary API secret
defaultFolderstringNoneDefault upload folder
maxSizeBytesnumberNoneMaximum allowed upload size in bytes (enforced while streaming; throws size-exceeded)
chunkSizenumber20 MiBChunk size for chunked uploads (clamped to a 5 MiB minimum). Files up to this size go up in one request.
cacheSizenumber1000Max public IDs whose resource type/version/format are cached in memory (least recently used evicted first)
deliveryType"upload" | "authenticated" | "private""upload"Delivery type for new uploads, and the type assumed when a lookup finds none (see Delivery types)

Metadata

CloudinaryDriver implements BaseDriver<CloudinaryMeta>

FieldTypeDescription
meta.publicIdstringCloudinary public ID
meta.versionnumberAsset version
meta.formatstringFile format
meta.resourceType"image" | "video" | "raw"Resource type
meta.deliveryType"upload" | "authenticated" | "private"Delivery type the asset was stored with
meta.bytesnumberFile size
meta.secureUrlstringHTTPS URL
meta.widthnumber | undefinedImage width
meta.heightnumber | undefinedImage height

Delivery types

Cloudinary assets are stored with one of three delivery types:

TypeWho can fetch the original
upload (default)Anyone with the URL.
authenticatedOnly via a signed URL. Transformed versions need one too.
privateOnly via a signed URL. Transformed versions are public.

Set the type for every upload in the driver config, or per upload:

const driver = new CloudinaryDriver({ cloudName, apiKey, apiSecret, deliveryType: "authenticated" });

// or per upload, overriding the driver default
await client.upload(stream, { filename: "contract.pdf", deliveryType: "private" });

The other methods follow the asset's delivery type automatically, using the same resolution chain as resource types (deliveryType hint → upload cache → Admin API lookup → driver default):

  • getUrl returns a plain CDN URL for upload assets and a signed URL for authenticated/private ones, since Cloudinary refuses unsigned requests for those. Signed URLs do not expire; use getPresignedUrl for links that should.
  • get streams through that same URL.
  • delete calls /resources/{resourceType}/{deliveryType}.
  • getPresignedUrl passes the type to the download API.

The same public ID can exist under several delivery types. Pass { deliveryType } to getUrl, get, delete, getPresignedUrl or getSignedUrl to choose one; the Admin API lookup is then filtered by that type.

meta.secureUrl is the URL Cloudinary returned, which is unsigned for authenticated/private assets; use getUrl instead.

URL Format

getUrl(publicId) returns a URL with the correct resource type and version:

https://res.cloudinary.com/{cloudName}/{resourceType}/upload/v{version}/{publicId}

The resource type (image, video, or raw) and version are resolved in this order:

  1. Explicit hint: getUrl(publicId, { resourceType, version }) skips all lookups.
  2. Upload cache: assets uploaded through this driver instance are tracked from the upload response.
  3. Admin API lookup: one resources/search request (Basic auth) for public IDs the instance hasn't seen, e.g. assets uploaded by another service or before a restart. The result is cached for subsequent calls, and the returned secure_url is used verbatim when available.
  4. image default: when nothing else matches, the URL is built assuming an image resource type.

Because a Cloudinary public ID does not encode its resource type, getUrl/delete of a video or raw asset uploaded outside this instance would otherwise silently build an incorrect /image/ URL or fail to delete. The Admin lookup resolves those cases without any caller cooperation.

Download

Stream an asset back from the CDN with get(publicId, options?): it fetches the asset's public URL and returns the response body as a WHATWG ReadableStream<Uint8Array>:

const stream = await client.get(result.meta.publicId);
const bytes = new Uint8Array(await new Response(stream).arrayBuffer());

The optional options argument is the same { resourceType, version } hint used by getUrl.

stream is a WHATWG ReadableStream<Uint8Array>, so you can also pipe it straight to its destination (stream.pipeTo(writable)) with no buffering. Use .arrayBuffer()/.blob() for binary files, because .text() would decode binary data as UTF-8 and corrupt it.

Throws with the HTTP status on a non-2xx response (e.g. 404 for a missing asset).

Presigned URLs

getPresignedUrl(publicId, { expiresIn, deliveryType }) returns a signed private download URL that stops working expiresIn seconds from now:

const url = await client.getPresignedUrl(result.meta.publicId, { expiresIn: 300 });
// https://api.cloudinary.com/v1_1/demo/image/download?public_id=sample&format=png&type=upload&expires_at=...&signature=...
  • It uses Cloudinary's private download API, which enforces expires_at for every delivery type. Delivery URLs on res.cloudinary.com cannot expire unless token-based authentication (a premium Cloudinary feature) is enabled.
  • The signature is a hex SHA-1 of the sorted parameters plus the API secret, generated with Web Crypto: no SDK and no network call. expiresIn defaults to 3600 and must be a positive integer.
  • The URL uses the same resolution chain as getUrl ({ resourceType, version, format } hints, upload cache, Admin API lookup) to pick the correct resource_type and format.
  • The delivery type is resolved like the resource type (see Delivery types); pass deliveryType to override it. It must match the asset's delivery type or Cloudinary returns 404.

Signed delivery URLs

CloudinaryDriver.getSignedUrl(publicId, { deliveryType }) returns a signed res.cloudinary.com URL (/s--SIG--/ component: the first 8 characters of a URL-safe base64 SHA-1 of the version, public ID and extension, plus the API secret). It is required for authenticated/private assets (getUrl returns it automatically for those) and does not expire; use getPresignedUrl for time-limited links.

Delete

delete(publicId, options?) removes an asset via the Cloudinary Admin API, using the same resolution chain as getUrl to pick the correct resource_type path (/resources/{type}/upload). Deleting an asset that does not exist is not an error. Any other failure (auth, network, rate limit, outage, including a failed Admin API lookup) throws a StorageError.

Cancellation

Pass an AbortSignal in UploadOptions to cancel an upload in flight:

const controller = new AbortController();

const upload = client.upload(stream, {
  filename: "large.mp4",
  signal: controller.signal,
});

// later...
controller.abort();

The signal is forwarded to the Cloudinary API request; on abort the driver rejects with a DOMException whose name is AbortError:

try {
  await upload;
} catch (err) {
  if (err instanceof DOMException && err.name === "AbortError") {
    // cancelled
  }
}

Cancellation takes effect both while reading the source stream and during each chunk's network request. A partially uploaded chunked upload is discarded by Cloudinary.

Progress

Pass onProgress to receive { bytes, total?, progress? } as the stream is read. Events track bytes leaving the source stream; for chunked uploads each chunk is sent as soon as it is read, so progress follows the upload closely (with options.size, progress reaches exactly 1 at the end):

const result = await client.upload(stream, {
  filename: "large.mp4",
  size: totalBytes,
  onProgress: ({ bytes, progress }) => {
    console.log(`${Math.round((progress ?? 0) * 100)}%`);
  },
});

Errors

All failures are StorageErrors from @fileway/core (see the error reference for the full contract: codes, statusCode, provider, cause, and isAbortError). For this driver:

CodeWhen
validationMalformed input: missing/oversized filename, path separators, absolute path, null bytes, malformed mimeType, non-positive expiresIn.
auth-failedHTTP 401/403: invalid or expired apiKey/apiSecret, or restricted permissions.
bucket-not-foundUpload-time HTTP 404: the cloud does not exist.
not-foundDownload-time HTTP 404: the asset does not exist at the CDN URL.
size-exceededUpload size exceeding maxSizeBytes, or HTTP 413.
conflictmove onto an existing public ID without overwrite: true.
rate-limitedAdmin API rate limit (HTTP 420) or HTTP 429. Safe to retry.
networkfetch failed before an HTTP response; the original error is preserved as cause. Safe to retry.
provider-errorAny other non-2xx response (e.g. HTTP 500). Safe to retry.

Was this page helpful?

On this page