Delete and restore a blob container with TypeScript

This article shows how to delete containers with the Azure Storage client library for JavaScript. If you've enabled container soft delete, you can restore deleted containers.

Prerequisites

  • The examples in this article assume you already have a project set up to work with the Azure Blob Storage client library for JavaScript. To learn about setting up your project, including package installation, importing modules, and creating an authorized client object to work with data resources, see Get started with Azure Blob Storage and TypeScript.
  • The authorization mechanism must have permissions to delete a blob container, or to restore a soft-deleted container. To learn more, see the authorization guidance for the following REST API operations:

Delete a container

To delete a container in TypeScript, create a BlobServiceClient or ContainerClient then use one of the following methods:

After you delete a container, you can't create a container with the same name for at least 30 seconds. Attempting to create a container with the same name will fail with HTTP error code 409 (Conflict). Any other operations on the container or the blobs it contains will fail with HTTP error code 404 (Not Found).

Delete container with BlobServiceClient

The following example deletes the specified container. Use the BlobServiceClient to delete a container:

// delete container immediately on blobServiceClient
async function deleteContainerImmediately(
  blobServiceClient: BlobServiceClient,
  containerName: string
): Promise<ContainerDeleteResponse> {
  return await blobServiceClient.deleteContainer(containerName);
}

Delete container with ContainerClient

The following example shows how to delete all of the containers whose name starts with a specified prefix using a ContainerClient.

async function deleteContainersWithPrefix(
  blobServiceClient: BlobServiceClient,
  prefix: string
): Promise<void> {
  const containerOptions: ServiceListContainersOptions = {
    // only delete containers not deleted
    includeDeleted: false,
    includeMetadata: false,
    includeSystem: true,
    prefix
  };

  for await (const containerItem of blobServiceClient.listContainers(
    containerOptions
  )) {
    try {
      const containerClient: ContainerClient =
        blobServiceClient.getContainerClient(containerItem.name);

      const containerDeleteMethodOptions: ContainerDeleteMethodOptions = {};

      await containerClient.delete(containerDeleteMethodOptions);

      console.log(`deleted ${containerItem.name} container - success`);
    } catch (err: unknown) {
      if (err instanceof Error) {
        console.log(
          `deleted ${containerItem.name} container - failed - ${err.message}`
        );
      }
    }
  }
}

Restore a deleted container

When container soft delete is enabled for a storage account, a container and its contents may be recovered after it has been deleted, within a retention period that you specify. You can restore a soft-deleted container using a BlobServiceClient object:

The following example finds a deleted container, gets the version ID of that deleted container, and then passes that ID into the undeleteContainer method to restore the container.

// Undelete specific container - last version
async function undeleteContainer(
  blobServiceClient: BlobServiceClient,
  containerName: string
): Promise<void> {
  // version to undelete
  let containerVersion: string | undefined;

  const containerOptions: ServiceListContainersOptions = {
    includeDeleted: true,
    prefix: containerName
  };

  // container listing returns version (timestamp) in the ContainerItem
  for await (const containerItem of blobServiceClient.listContainers(
    containerOptions
  )) {
    // if there are multiple deleted versions of the same container,
    // the versions are in asc time order
    // the last version is the most recent
    if (containerItem.name === containerName) {
      containerVersion = containerItem.version as string;
    }
  }

  if (containerVersion !== undefined) {
    const serviceUndeleteContainerOptions: ServiceUndeleteContainerOptions = {};

    const {
      containerClient,
      containerUndeleteResponse
    }: {
      containerClient: ContainerClient;
      containerUndeleteResponse: ContainerUndeleteResponse;
    } = await blobServiceClient.undeleteContainer(
      containerName,
      containerVersion,

      // optional/new container name - if unused, original container name is used
      //newContainerName
      serviceUndeleteContainerOptions
    );

    // Check delete
    if (containerUndeleteResponse.errorCode)
      throw Error(containerUndeleteResponse.errorCode);

    // undelete was successful
    console.log(`${containerName} is undeleted`);

    // do something with containerClient
    // ...
    // containerClient.listBlobsFlat({    includeMetadata: true,
    // includeSnapshots: false,
    // includeTags: true,
    // includeVersions: false,
    // prefix: ''});
  }
}

Resources

To learn more about deleting a container using the Azure Blob Storage client library for JavaScript, see the following resources.

REST API operations

The Azure SDK for JavaScript contains libraries that build on top of the Azure REST API, allowing you to interact with REST API operations through familiar JavaScript paradigms. The client library methods for deleting or restoring a container use the following REST API operations:

Code samples

Client library resources

See also