Upload SDK

API Reference

Reference for the functions, provider factories, uploader methods, and error helpers exported by Upload SDK.

Import core APIs and provider factories from:

import {
  UploadSDKError,
  createUploader,
  defineAssets,
  defineStorageProfiles,
  defineUploadConfig,
  isUploadSDKError,
  toUploadSDKError,
} from "@marinedotsh/upload-sdk";
import { awsS3, imageKit } from "@marinedotsh/upload-sdk/providers";

defineStorageProfiles()

Defines named provider configurations and preserves their names for TypeScript.

function defineStorageProfiles<
  const TStorageProfiles extends Record<
    string,
    StorageProvider
  >,
>(
  storageProfiles: TStorageProfiles,
): TStorageProfiles

Parameters

ParameterDescription
storageProfilesAn object containing named provider configurations

Returns

The same object passed to the function.

defineStorageProfiles() does not change the profiles or validate provider credentials. Its main purpose is to preserve profile names for type checking.

Example

const storageProfiles = defineStorageProfiles({
  userUploads: awsS3({
    bucket: process.env.AWS_BUCKET!,
    region: process.env.AWS_REGION!,
    credentials: {
      accessKeyId: process.env.AWS_ACCESS_KEY_ID!,
      secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!,
    },
  }),
});

See Storage Profiles.

defineAssets()

Defines named upload assets and connects their storageProfile values to the available storage profiles.

function defineAssets<
  const TStorageProfiles extends Record<
    string,
    StorageProvider
  >,
  const TAssets extends Record<
    string,
    AssetUploadConfig<
      keyof TStorageProfiles & string
    >
  >,
>(
  storageProfiles: TStorageProfiles,
  assets: TAssets,
): TAssets

Parameters

ParameterDescription
storageProfilesThe profiles created with defineStorageProfiles()
assetsNamed upload asset configurations

Returns

The same asset object passed to the function.

defineAssets() preserves asset names and checks profile references through TypeScript. Runtime validation happens later when prepareUpload() is called.

Example

const assets = defineAssets(storageProfiles, {
  avatar: {
    storageProfile: "userUploads",
    keyPrefix: "avatars",
    accept: {
      mimeTypes: ["image/png", "image/jpeg"],
      extensions: [".png", ".jpg", ".jpeg"],
    },
    limits: {
      maxFileSize: {
        value: 2,
        unit: "MB",
      },
    },
  },
});

See Upload Assets.

defineUploadConfig()

Defines the complete uploader configuration as one object.

function defineUploadConfig<
  const TStorageProfiles extends Record<
    string,
    StorageProvider
  >,
  const TAssets extends Record<
    string,
    AssetUploadConfig<
      keyof TStorageProfiles & string
    >
  >,
>(config: {
  storageProfiles: TStorageProfiles;
  defaultStorageProfile:
    keyof TStorageProfiles & string;
  assets: TAssets;
}): {
  storageProfiles: TStorageProfiles;
  defaultStorageProfile:
    keyof TStorageProfiles & string;
  assets: TAssets;
}

Parameters

PropertyDescription
storageProfilesNamed provider configurations
defaultStorageProfileProfile used when an asset does not select one
assetsNamed upload asset configurations

Returns

The same configuration object passed to the function.

Example

const uploadConfig = defineUploadConfig({
  storageProfiles,
  defaultStorageProfile: "userUploads",
  assets,
});

The result can be passed directly to createUploader():

const uploader = createUploader(uploadConfig);

createUploader()

Creates an uploader from storage profiles and upload assets.

const uploader = createUploader({
  storageProfiles,
  defaultStorageProfile,
  assets,
});

Parameters

PropertyDescription
storageProfilesProfiles created with defineStorageProfiles()
defaultStorageProfileProfile used when an asset does not select one
assetsAssets created with defineAssets()

defaultStorageProfile must match a name in storageProfiles.

Returns

An uploader with a prepareUpload() method:

{
  prepareUpload(
    assetName,
    input,
  ): Promise<PrepareUploadOutput>
}

Example

export const uploader = createUploader({
  storageProfiles,
  defaultStorageProfile: "userUploads",
  assets,
});

uploader.prepareUpload()

Validates client-reported file information and asks the selected provider to create a signed upload target.

uploader.prepareUpload(
  assetName,
  input,
): Promise<PrepareUploadOutput>

Parameters

assetName

The name of an asset passed to defineAssets().

"avatar"

Asset names are checked by TypeScript.

input

{
  filename: string;
  contentType: string;
  size: number;
}
PropertyDescription
filenameClient-reported filename
contentTypeClient-reported MIME type
sizeClient-reported size in bytes

Returns

A promise that resolves to PrepareUploadOutput.

const preparedUpload =
  await uploader.prepareUpload("avatar", {
    filename: "profile.png",
    contentType: "image/png",
    size: 120_000,
  });

Throws

Throws an UploadSDKError when validation, configuration, or provider preparation fails.

try {
  const preparedUpload =
    await uploader.prepareUpload("avatar", input);
} catch (error) {
  if (isUploadSDKError(error)) {
    console.error(error.code, error.message);
  }
}

See Prepared Uploads.

awsS3()

Creates an AWS S3 provider.

function awsS3(
  config: AwsS3Config,
): StorageProvider

Configuration

type AwsS3Config = {
  bucket: string;
  region: string;
  credentials: {
    accessKeyId: string;
    secretAccessKey: string;
    sessionToken?: string;
  };
};
PropertyRequiredDescription
bucketYesS3 bucket name
regionYesAWS region containing the bucket
credentials.accessKeyIdYesAWS access key ID
credentials.secretAccessKeyYesAWS secret access key
credentials.sessionTokenNoSession token for temporary credentials

Example

const provider = awsS3({
  bucket: process.env.AWS_BUCKET!,
  region: process.env.AWS_REGION!,
  credentials: {
    accessKeyId: process.env.AWS_ACCESS_KEY_ID!,
    secretAccessKey:
      process.env.AWS_SECRET_ACCESS_KEY!,
    sessionToken: process.env.AWS_SESSION_TOKEN,
  },
});

Keep AWS credentials in server-only code.

See AWS S3.

imageKit()

Creates an ImageKit provider.

function imageKit(
  config: ImageKitConfig,
): StorageProvider

Configuration

type ImageKitConfig = {
  publicKey: string;
  privateKey: string;
};
PropertyRequiredDescription
publicKeyYesImageKit public key
privateKeyYesImageKit private key used for signing

Example

const provider = imageKit({
  publicKey: process.env.IMAGEKIT_PUBLIC_KEY!,
  privateKey: process.env.IMAGEKIT_PRIVATE_KEY!,
});

Keep the private key in server-only code.

See ImageKit.

isUploadSDKError()

Checks whether an unknown value is an UploadSDKError.

function isUploadSDKError(
  error: unknown,
): error is UploadSDKError

Parameters

ParameterDescription
errorThe value to check

Returns

true when the value is an UploadSDKError.

Example

try {
  await uploader.prepareUpload("avatar", input);
} catch (error) {
  if (isUploadSDKError(error)) {
    console.error({
      code: error.code,
      message: error.message,
      statusCode: error.statusCode,
      details: error.details,
    });
  }
}

UploadSDKError

The error class used for expected SDK failures.

class UploadSDKError extends Error {
  readonly code: UploadSDKErrorCode;
  readonly statusCode: number;
  readonly details?: unknown;
}

Constructor

new UploadSDKError(message, {
  code,
  statusCode,
  cause,
  details,
});
ParameterRequiredDescription
messageYesReadable error message
codeYesMachine-readable SDK error code
statusCodeNoSuggested HTTP status
causeNoOriginal error
detailsNoExtra diagnostic information

Example

throw new UploadSDKError(
  "The reported file type is not allowed.",
  {
    code: "INVALID_UPLOAD_INPUT",
    statusCode: 400,
  },
);

The default status is 400 for INVALID_UPLOAD_INPUT and 500 for other SDK error codes.

Most applications should catch errors created by the SDK rather than create them directly.

toUploadSDKError()

Converts an unknown error into an UploadSDKError.

function toUploadSDKError(
  error: unknown,
  fallback: {
    code: UploadSDKErrorCode;
    message: string;
    statusCode?: number;
    details?: unknown;
  },
): UploadSDKError

When error is already an UploadSDKError, it is returned unchanged.

Otherwise, the function creates a new error using the fallback values and keeps the original error as its cause.

Example

try {
  await performOperation();
} catch (error) {
  throw toUploadSDKError(error, {
    code: "UPLOAD_PROVIDER_ERROR",
    message: "Upload could not be prepared.",
    statusCode: 500,
  });
}

Most applications only need isUploadSDKError(). toUploadSDKError() is useful when normalizing errors in server-side SDK integrations.

Error codes

type UploadSDKErrorCode =
  | "INVALID_UPLOAD_INPUT"
  | "INVALID_UPLOAD_CONFIG"
  | "UNSUPPORTED_UPLOAD_OPERATION"
  | "UPLOAD_PROVIDER_ERROR";
CodeMeaning
INVALID_UPLOAD_INPUTReported file information is invalid or not allowed
INVALID_UPLOAD_CONFIGAsset or provider configuration is invalid
UNSUPPORTED_UPLOAD_OPERATIONThe selected operation is not supported
UPLOAD_PROVIDER_ERRORThe provider could not prepare the upload

See Validation and Errors for error-handling examples.

Next steps

On this page