# Using the SDK

Before you can use the SDK, make sure that you have followed the steps in the [Getting Started](/docs/sdks/tigris/.md#getting-started) guide.

## Authentication[​](#authentication "Direct link to Authentication")

After you have created an access key, you can set the environment variables in your `.env` file:

```
TIGRIS_STORAGE_ACCESS_KEY_ID=tid_access_key_id

TIGRIS_STORAGE_SECRET_ACCESS_KEY=tsec_secret_access_key

TIGRIS_STORAGE_BUCKET=bucket_name
```

Alternatively, all methods accept an optional config parameter that allows you to override the default environment configuration:

```
type TigrisStorageConfig = {

  bucket?: string;

  accessKeyId?: string;

  secretAccessKey?: string;

  endpoint?: string;

};
```

### Examples[​](#examples "Direct link to Examples")

#### Use environment variables (default)[​](#use-environment-variables-default "Direct link to Use environment variables (default)")

```
const result = await list();
```

#### Override with custom config[​](#override-with-custom-config "Direct link to Override with custom config")

```
const result = await list({

  config: {

    bucket: "my-bucket-name",

    accessKeyId: "tigris-access-key",

    secretAccessKey: "tigris-secret-key",

  },

});
```

#### Override only specific values[​](#override-only-specific-values "Direct link to Override only specific values")

```
const result = await get("object.txt", "string", {

  config: {

    bucket: "different-bucket",

  },

});
```

## Responses[​](#responses "Direct link to Responses")

All methods return a generic response of type `TigrisStorageResponse`. If there is an error, the `error` property will be set. If there is a successful response, the `data` property will be set. This allows for a better type safety and error handling.

```
type TigrisStorageResponse<T, E> = {

  data?: T;

  error?: E;

};
```

### Example[​](#example "Direct link to Example")

```
const objectResult = await get("photo.jpg", "file");

if (objectResult.error) {

  console.error("Error downloading object:", objectResult.error);

} else {

  console.log("Object name:", objectResult.data?.name);

  console.log("Object size:", objectResult.data?.size);

  console.log("Object type:", objectResult.data?.type);

}
```

## Uploading an object[​](#uploading-an-object "Direct link to Uploading an object")

`put` function can be used to upload a object to a bucket.

### `put`[​](#put "Direct link to put")

```
put(path: string, body: string | ReadableStream | Blob | Buffer, options?: PutOptions): Promise<TigrisStorageResponse<PutResponse, Error>>;
```

`put` accepts the following parameters:

* `path`: (Required) A string specifying the base value of the return URL
* `body`: (Required) A blob object as ReadableStream, String, ArrayBuffer or Blob based on these supported body types
* `options`: (Optional) A JSON object with the following optional parameters:

#### `options`[​](#options "Direct link to options")

| **Parameter**      | **Required** | **Values**                                                                                                                                              |
| ------------------ | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| access             | No           | The access level for the object. Possible values are `public` and `private`.                                                                            |
| addRandomSuffix    | No           | Whether to add a random suffix to the object name. Default is `false`.                                                                                  |
| allowOverwrite     | No           | Whether to allow overwriting the object. Default is `true`.                                                                                             |
| contentType        | No           | Set the content type of the object. If not provided, the content type will be inferred from the extension of the path.                                  |
| contentDisposition | No           | Set the content disposition of the object. Possible values are `inline` and `attachment`. Default is `inline`. Use `attachment` for downloadable files. |
| multipart          | No           | Pass `multipart: true` when uploading large objects. It will split the object into multiple parts and upload them in parallel.                          |
| abortController    | No           | An AbortController instance to abort the upload.                                                                                                        |
| onUploadProgress   | No           | Callback to track upload progress: `onUploadProgress({loaded: number, total: number, percentage: number})`.                                             |
| config             | No           | A configuration object to override the [default configuration](#authentication).                                                                        |

In case of successful upload, the `data` property will be set to the upload and contains the following properties:

* `contentDisposition`: content disposition of the object
* `contentType`: content type of the object
* `modified`: Last modified date of the object
* `path`: Path to the object
* `size`: Size of the object
* `url`: A presigned URL to the object if the object is uploaded with `access` set to `private`, otherwise unsigned public URL for the object

### Examples[​](#examples-1 "Direct link to Examples")

#### Simple upload[​](#simple-upload "Direct link to Simple upload")

```
const result = await put("simple.txt", "Hello, World!");

if (result.error) {

  console.error("Error uploading object:", result.error);

} else {

  console.log("Object uploaded successfully:", result.data);

}
```

#### Uploading a large object[​](#uploading-a-large-object "Direct link to Uploading a large object")

```
const result = await put("large.mp4", fileStream, {

  multipart: true,

  onUploadProgress: ({ loaded, total, percentage }) => {

    console.log(`Uploaded ${loaded} of ${total} bytes (${percentage}%)`);

  },

});
```

#### Prevent overwriting[​](#prevent-overwriting "Direct link to Prevent overwriting")

```
const result = await put("config.json", configuration, {

  allowOverwrite: false,

});
```

#### Cancel an upload[​](#cancel-an-upload "Direct link to Cancel an upload")

```
const abortController = new AbortController();



const result = await put("large.mp4", fileStream, {

  abortController: abortController,

});



function cancelUpload() {

  abortController.abort();

}



// <button onClick={cancelUpload}>Cancel Upload</button>
```

## Downloading an object[​](#downloading-an-object "Direct link to Downloading an object")

`get` function can be used to get/download a object from a bucket.

### `get`[​](#get "Direct link to get")

```
get(path: string, format: "string" | "file" | "stream", options?: GetOptions): Promise<TigrisStorageResponse<GetResponse, Error>>;
```

`get` accepts the following parameters:

* `path`: (Required) A string specifying the path to the object
* `format`: (Required) A string specifying the format of the object. Possible values are `string`, `file`, and `stream`.
* `options`: (Optional) A JSON object with the following optional parameters:

#### `options`[​](#options-1 "Direct link to options-1")

| **Parameter**      | **Required** | **Values**                                                                                                                                              |
| ------------------ | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| contentDisposition | No           | Set the content disposition of the object. Possible values are `inline` and `attachment`. Default is `inline`. Use `attachment` for downloadable files. |
| contentType        | No           | Set the content type of the object. If not provided, content type set when the object is uploaded will be used.                                         |
| encoding           | No           | Set the encoding of the object. Default is `utf-8`.                                                                                                     |
| config             | No           | A configuration object to override the [default configuration](#authentication).                                                                        |

In case of successful `get`, the `data` contains the object in the format specified by the `format` parameter.

### Examples[​](#examples-2 "Direct link to Examples")

#### Get an object as a string[​](#get-an-object-as-a-string "Direct link to Get an object as a string")

```
const result = await get("object.txt", "string");



if (result.error) {

  console.error("Error getting object:", result.error);

} else {

  console.log("Object:", result.data);

  // output: "Hello, World!"

}
```

#### Get an object as a file[​](#get-an-object-as-a-file "Direct link to Get an object as a file")

```
const result = await get("object.pdf", "file", {

  contentDisposition: "attachment",

  contentType: "application/pdf",

  encoding: "utf-8",

});



if (result.error) {

  console.error("Error getting object:", result.error);

} else {

  console.log("Object:", result.data);

}
```

#### Get an object as a stream[​](#get-an-object-as-a-stream "Direct link to Get an object as a stream")

```
const result = await get("video.mp4", "stream", {

  contentDisposition: "attachment",

  contentType: "video/mp4",

  encoding: "utf-8",

});



if (result.error) {

  console.error("Error getting object:", result.error);

} else {

  const reader = result.data?.getReader();

  // Process stream...

  reader?.read().then((result) => {

    console.log(result);

  });

}
```

## Object metadata[​](#object-metadata "Direct link to Object metadata")

`head` function can be used to get the metadata of an object from a bucket.

### `head`[​](#head "Direct link to head")

```
head(path: string, options?: HeadOptions): Promise<TigrisStorageResponse<HeadResponse, Error>>
```

`head` accepts the following parameters:

* `path`: (Required) A string specifying the path to the object
* `options`: (Optional) A JSON object with the following optional parameters:

#### `options`[​](#options-2 "Direct link to options-2")

| **Parameter** | **Required** | **Values**                                                                       |
| ------------- | ------------ | -------------------------------------------------------------------------------- |
| config        | No           | A configuration object to override the [default configuration](#authentication). |

In case of successful `head`, the `data` property will be set to the metadata of the object and contains the following properties:

* `contentDisposition`: content disposition of the object
* `contentType`: content type of the object
* `modified`: Last modified date of the object
* `path`: Path to the object
* `size`: Size of the object
* `url`: A presigned URL to the object if the object is downloaded with `access` set to `private`, otherwise unsigned public URL for the object

### Examples[​](#examples-3 "Direct link to Examples")

#### Get object metadata[​](#get-object-metadata "Direct link to Get object metadata")

```
const result = await head("object.txt");



if (result.error) {

  console.error("Error getting object metadata:", result.error);

} else {

  console.log("Object metadata:", result.data);

  // output: {

  //   contentDisposition: "inline",

  //   contentType: "text/plain",

  //   modified: "2023-01-15T08:30:00Z",

  //   path: "object.txt",

  //   size: 12,

  //   url: "https://tigris-example.t3.storage.dev/object.txt",

  // }

}
```

## Deleting an object[​](#deleting-an-object "Direct link to Deleting an object")

`remove` function can be used to delete an object from a bucket.

### `remove`[​](#remove "Direct link to remove")

```
remove(path: string, options?: RemoveOptions): Promise<TigrisStorageResponse<void, Error>>;
```

`remove` accepts the following parameters:

* `path`: (Required) A string specifying the path to the object
* `options`: (Optional) A JSON object with the following optional parameters:

#### `options`[​](#options-3 "Direct link to options-3")

| **Parameter** | **Required** | **Values**                                                                       |
| ------------- | ------------ | -------------------------------------------------------------------------------- |
| config        | No           | A configuration object to override the [default configuration](#authentication). |

In case of successful `remove`, the `data` property will be set to `undefined` and the object will be deleted.

### Examples[​](#examples-4 "Direct link to Examples")

#### Delete an object[​](#delete-an-object "Direct link to Delete an object")

```
const result = await remove("object.txt");



if (result.error) {

  console.error("Error deleting object:", result.error);

} else {

  console.log("Object deleted successfully");

}
```

## Presigning an object[​](#presigning-an-object "Direct link to Presigning an object")

`getPresignedUrl` function can be used to presign an object from a bucket and retreive the presigned URL.

### `getPresignedUrl`[​](#getpresignedurl "Direct link to getpresignedurl")

```
getPresignedUrl(path: string, options: GetPresignedUrlOptions): Promise<TigrisStorageResponse<GetPresignedUrlResponse, Error>>
```

`getPresignedUrl` accepts the following parameters:

* `path`: (Required) A string specifying the path to the object
* `options`: (Optional) A JSON object with the following optional parameters:

#### `options`[​](#options-4 "Direct link to options-4")

| **Parameter** | **Required** | **Values**                                                                               |
| ------------- | ------------ | ---------------------------------------------------------------------------------------- |
| operation     | No           | Specify the operation to use for the presigned URL. Possible values are `get` and `put`. |
| expiresIn     | No           | The expiration time of the presigned URL in seconds. Default is 3600 seconds (1 hour).   |
| contentType   | No           | The content type of the object.                                                          |
| config        | No           | A configuration object to override the [default configuration](#authentication).         |

In case of successful `getPresignedUrl`, the `data` property will be set to the presigned URL and contains the following properties:

* `url`: The presigned URL
* `method`: The method used to get the presigned URL
* `expiresIn`: The expiration time of the presigned URL

### Examples[​](#examples-5 "Direct link to Examples")

#### Get a presigned URL for a GET operation[​](#get-a-presigned-url-for-a-get-operation "Direct link to Get a presigned URL for a GET operation")

```
const result = await getPresignedUrl("object.txt", { operation: "get" });



if (result.error) {

  console.error("Error getting presigned URL:", result.error);

} else {

  console.log("Presigned URL:", result.data.url);

}
```

#### Get a presigned URL for a PUT operation[​](#get-a-presigned-url-for-a-put-operation "Direct link to Get a presigned URL for a PUT operation")

```
const result = await getPresignedUrl("object.txt", { operation: "put" });
```

## Listing objects[​](#listing-objects "Direct link to Listing objects")

`list` function can be used to list objects from a bucket.

### `list`[​](#list "Direct link to list")

```
list(options?: ListOptions): Promise<TigrisStorageResponse<ListResponse, Error>>;
```

`list` accepts the following parameters:

* `options`: (Optional) A JSON object with the following optional parameters:

#### `options`[​](#options-5 "Direct link to options-5")

| **Parameter**                             | **Required** | **Values**                                                                      |
| ----------------------------------------- | ------------ | ------------------------------------------------------------------------------- |
| delimiter                                 | No           | A delimiter is a character that you use to group keys.                          |
| prefix                                    | No           | Limits the items to keys that begin with the specified prefix.                  |
| limit                                     | No           | The maximum number of objects to return. By default, returns up to 100 objects. |
| paginationToken                           | No           | The pagination token to continue listing objects from the previous request.     |
| config                                    | No           | A configuration object to override the                                          |
| [default configuration](#authentication). |              |                                                                                 |

In case of successful `list`, the `data` property will be set to the list of objects and contains the following properties:

* `items`: The list of objects
* `paginationToken`: The pagination token to continue listing objects for next page.
* `hasMore`: Whether there are more objects to list.

### Examples[​](#examples-6 "Direct link to Examples")

#### List objects[​](#list-objects "Direct link to List objects")

```
const result = await list();



if (result.error) {

  console.error("Error listing objects:", result.error);

} else {

  console.log("Objects:", result.data);

}
```

#### List objects with pagination[​](#list-objects-with-pagination "Direct link to List objects with pagination")

```
const allFiles: Item[] = [];

let currentPage = await list({ limit: 10 });



if (currentPage.data) {

  allFiles.push(...currentPage.data.items);



  while (currentPage.data?.hasMore && currentPage.data?.paginationToken) {

    currentPage = await list({

      limit: 10,

      paginationToken: currentPage.data?.paginationToken,

    });



    if (currentPage.data) {

      allFiles.push(...currentPage.data.items);

    } else if (currentPage.error) {

      console.error("Error during pagination:", currentPage.error);

      break;

    }

  }

}



console.log(allFiles);
```

## Creating a bucket[​](#creating-a-bucket "Direct link to Creating a bucket")

`createBucket` function can be used to create a new bucket.

### `createBucket`[​](#createbucket "Direct link to createbucket")

```
createBucket(bucketName: string, options?: CreateBucketOptions): Promise<TigrisStorageResponse<CreateBucketResponse, Error>>;
```

`createBucket` accepts the following parameters:

* `bucketName`: (Required) A string specifying the name of the bucket to create
* `options`: (Optional) A JSON object with the following optional parameters:

#### `options`[​](#options-6 "Direct link to options-6")

| **Parameter**        | **Required** | **Values**                                                                       |
| -------------------- | ------------ | -------------------------------------------------------------------------------- |
| enableSnapshot       | No           | Enable snapshot functionality for the bucket. Default is `false`.                |
| sourceBucketName     | No           | The name of the source bucket to fork from.                                      |
| sourceBucketSnapshot | No           | The snapshot version of the source bucket to fork from.                          |
| config               | No           | A configuration object to override the [default configuration](#authentication). |

In case of successful `createBucket`, the `data` property will be set and contains the following properties:

* `isSnapshotEnabled`: Whether snapshot functionality is enabled for the bucket
* `hasForks`: Whether the bucket has forks
* `sourceBucketName`: The name of the source bucket (if this is a fork bucket)
* `sourceBucketSnapshot`: The snapshot version of the source bucket (if this is a fork bucket)

### Examples[​](#examples-7 "Direct link to Examples")

#### Create a regular bucket[​](#create-a-regular-bucket "Direct link to Create a regular bucket")

```
const result = await createBucket("my-new-bucket");



if (result.error) {

  console.error("Error creating bucket:", result.error);

} else {

  console.log("Bucket created successfully:", result.data);

}
```

#### Create a bucket with snapshot enabled[​](#create-a-bucket-with-snapshot-enabled "Direct link to Create a bucket with snapshot enabled")

```
const result = await createBucket("my-snapshot-bucket", {

  enableSnapshot: true,

});



if (result.error) {

  console.error("Error creating bucket:", result.error);

} else {

  console.log("Bucket created with snapshot enabled:", result.data);

}
```

## Getting bucket information[​](#getting-bucket-information "Direct link to Getting bucket information")

`getBucketInfo` function can be used to retrieve information about a specific bucket.

### `getBucketInfo`[​](#getbucketinfo "Direct link to getbucketinfo")

```
getBucketInfo(bucketName: string, options?: GetBucketInfoOptions): Promise<TigrisStorageResponse<BucketInfoResponse, Error>>;
```

`getBucketInfo` accepts the following parameters:

* `bucketName`: (Required) A string specifying the name of the bucket
* `options`: (Optional) A JSON object with the following optional parameters:

#### `options`[​](#options-7 "Direct link to options-7")

| **Parameter** | **Required** | **Values**                                                                       |
| ------------- | ------------ | -------------------------------------------------------------------------------- |
| config        | No           | A configuration object to override the [default configuration](#authentication). |

In case of successful `getBucketInfo`, the `data` property will be set and contains the following properties:

* `isSnapshotEnabled`: Whether snapshot is enabled for the bucket
* `hasForks`: Whether the bucket has forks
* `sourceBucketName`: The name of the source bucket (if the bucket is a fork)
* `sourceBucketSnapshot`: The snapshot version of the source bucket (if the bucket is a fork)

### Examples[​](#examples-8 "Direct link to Examples")

#### Get bucket information[​](#get-bucket-information "Direct link to Get bucket information")

```
const result = await getBucketInfo("my-bucket");



if (result.error) {

  console.error("Error getting bucket info:", result.error);

} else {

  console.log("Bucket info:", result.data);

  // output: {

  //   isSnapshotEnabled: true,

  //   hasForks: false,

  //   sourceBucketName: undefined,

  //   sourceBucketSnapshot: undefined

  // }

}
```

## Listing buckets[​](#listing-buckets "Direct link to Listing buckets")

`listBuckets` function can be used to list all buckets that the user has access to.

### `listBuckets`[​](#listbuckets "Direct link to listbuckets")

```
listBuckets(options?: ListBucketsOptions): Promise<TigrisStorageResponse<ListBucketsResponse, Error>>;
```

`listBuckets` accepts the following parameters

* `options`: (Optional) A JSON object with the following optional parameters:

#### `options`[​](#options-8 "Direct link to options-8")

| **Parameter**   | **Required** | **Values**                                                                       |
| --------------- | ------------ | -------------------------------------------------------------------------------- |
| limit           | No           | The maximum number of buckets to return.                                         |
| paginationToken | No           | The pagination token to continue listing buckets from the previous request.      |
| config          | No           | A configuration object to override the [default configuration](#authentication). |

In case of successful `listBuckets`, the `data` property will be set to the list of buckets and will contain the following properties:

* `buckets`: The list of buckets
* `owner`: The owner of the buckets
* `paginationToken`: The pagination token to continue listing buckets for the next page.

### Examples[​](#examples-9 "Direct link to Examples")

#### Listing buckets[​](#listing-buckets-1 "Direct link to Listing buckets")

```
const result = await listBuckets();



if (result.error) {

  console.error("Error listing buckets:", result.error);

} else {

  console.log("Buckets:", result.data);

}
```

## Deleting a bucket[​](#deleting-a-bucket "Direct link to Deleting a bucket")

`removeBucket` function can be used to delete a bucket.

### `removeBucket`[​](#removebucket "Direct link to removebucket")

```
removeBucket(bucketName: string, options?: RemoveBucketOptions): Promise<TigrisStorageResponse<void, Error>>;
```

`removeBucket` accepts the following parameters:

* `bucketName`: (Required) A string specifying the name of the bucket
* `options`: (Optional) A JSON object with the following optional parameters:

#### `options`[​](#options-9 "Direct link to options-9")

| **Parameter** | **Required** | **Values**                                                                       |
| ------------- | ------------ | -------------------------------------------------------------------------------- |
| force         | No           | When provided, forcefully delete the bucket.                                     |
| config        | No           | A configuration object to override the [default configuration](#authentication). |

In case of successful `removeBucket`, the `data` property will be set to `undefined` and the bucket will be deleted.

### Examples[​](#examples-10 "Direct link to Examples")

#### Deleting a bucket[​](#deleting-a-bucket-1 "Direct link to Deleting a bucket")

```
const result = await removeBucket("my-bucket");



if (result.error) {

  console.error("Error deleting bucket:", result.error);

} else {

  console.log("Bucket deleted successfully");

}
```
