Quickstart: Manage blobs with JavaScript v12 SDK in a browser
Azure Blob storage is optimized for storing large amounts of unstructured data. Blobs are objects that can hold text or binary data, including images, documents, streaming media, and archive data. In this quickstart, you learn to manage blobs by using JavaScript in a browser. You'll upload and list blobs, and you'll create and delete containers.
Additional resources:
Prerequisites
- An Azure account with an active subscription
- An Azure Storage account
- Node.js
- Microsoft Visual Studio Code
- A Visual Studio Code extension for browser debugging, such as:
Object model
Blob storage offers three types of resources:
- The storage account
- A container in the storage account
- A blob in the container
The following diagram shows the relationship between these resources.

In this quickstart, you'll use the following JavaScript classes to interact with these resources:
- BlobServiceClient: The
BlobServiceClientclass allows you to manipulate Azure Storage resources and blob containers. - ContainerClient: The
ContainerClientclass allows you to manipulate Azure Storage containers and their blobs. - BlockBlobClient: The
BlockBlobClientclass allows you to manipulate Azure Storage blobs.
Setting up
This section walks you through preparing a project to work with the Azure Blob storage client library v12 for JavaScript.
Create a CORS rule
Before your web application can access blob storage from the client, you must configure your account to enable cross-origin resource sharing, or CORS.
In the Azure portal, select your storage account. To define a new CORS rule, navigate to the Settings section and select CORS. For this quickstart, you create an open CORS rule:

The following table describes each CORS setting and explains the values used to define the rule.
| Setting | Value | Description |
|---|---|---|
| ALLOWED ORIGINS | * | Accepts a comma-delimited list of domains set as acceptable origins. Setting the value to * allows all domains access to the storage account. |
| ALLOWED METHODS | DELETE, GET, HEAD, MERGE, POST, OPTIONS, and PUT | Lists the HTTP verbs allowed to execute against the storage account. For the purposes of this quickstart, select all available options. |
| ALLOWED HEADERS | * | Defines a list of request headers (including prefixed headers) allowed by the storage account. Setting the value to * allows all headers access. |
| EXPOSED HEADERS | * | Lists the allowed response headers by the account. Setting the value to * allows the account to send any header. |
| MAX AGE | 86400 | The maximum amount of time the browser caches the preflight OPTIONS request in seconds. A value of 86400 allows the cache to remain for a full day. |
After you fill in the fields with the values from this table, click the Save button.
Important
Ensure any settings you use in production expose the minimum amount of access necessary to your storage account to maintain secure access. The CORS settings described here are appropriate for a quickstart as it defines a lenient security policy. These settings, however, are not recommended for a real-world context.
Create a shared access signature
The shared access signature (SAS) is used by code running in the browser to authorize Azure Blob storage requests. By using the SAS, the client can authorize access to storage resources without the account access key or connection string. For more information on SAS, see Using shared access signatures (SAS).
Follow these steps to get the Blob service SAS URL:
- In the Azure portal, select your storage account.
- Navigate to the Security + networking section and select Shared access signature.
- Scroll down and click the Generate SAS and connection string button.
- Scroll down further and locate the Blob service SAS URL field
- Click the Copy to clipboard button at the far-right end of the Blob service SAS URL field.
- Save the copied URL somewhere for use in an upcoming step.
Add the Azure Blob storage client library
On your local computer, create a new folder called azure-blobs-js-browser and open it in Visual Studio Code.
Select View > Terminal to open a console window inside Visual Studio Code. Run the following Node.js Package Manager (npm) command in the terminal window to create a package.json file.
npm init -y
The Azure SDK is composed of many separate packages. You can choose which packages you need based on the services you intend to use. Run following npm command in the terminal window to install the @azure/storage-blob package.
npm install --save @azure/storage-blob
Bundle the Azure Blob storage client library
To use Azure SDK libraries on a website, convert your code to work inside the browser. You do this using a tool called a bundler. Bundling takes JavaScript code written using Node.js conventions and converts it into a format that's understood by browsers. This quickstart article uses the Parcel bundler.
Install Parcel by running the following npm command in the terminal window:
npm install -g parcel-bundler
In Visual Studio Code, open the package.json file and add a browserlist between the license and dependencies entries. This browserlist targets the latest version of three popular browsers. The full package.json file should now look like this:
{
"name": "azure-blobs-javascript",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"browserslist": [
"last 1 Edge version",
"last 1 Chrome version",
"last 1 Firefox version"
],
"dependencies": {
"@azure/storage-blob": "^12.1.1"
}
}
Save the package.json file.
Import the Azure Blob storage client library
To use Azure SDK libraries inside JavaScript, import the @azure/storage-blob package. Create a new file in Visual Studio Code containing the following JavaScript code.
// index.js
const { BlobServiceClient } = require("@azure/storage-blob");
// Now do something interesting with BlobServiceClient
Save the file as index.js in the azure-blobs-js-browser directory.
Implement the HTML page
Create a new file in Visual Studio Code and add the following HTML code.
<!-- index.html -->
<!DOCTYPE html>
<html>
<body>
<button id="create-container-button">Create container</button>
<button id="delete-container-button">Delete container</button>
<button id="select-button">Select and upload files</button>
<input type="file" id="file-input" multiple style="display: none;" />
<button id="list-button">List files</button>
<button id="delete-button">Delete selected files</button>
<p><b>Status:</b></p>
<p id="status" style="height:160px; width: 593px; overflow: scroll;" />
<p><b>Files:</b></p>
<select id="file-list" multiple style="height:222px; width: 593px; overflow: scroll;" />
</body>
<script src="./index.js"></script>
</html>
Save the file as index.html in the azure-blobs-js-browser folder.
Code examples
The example code shows you how to accomplish the following tasks with the Azure Blob storage client library for JavaScript:
- Declare fields for UI elements
- Add your storage account info
- Create client objects
- Create and delete a storage container
- List blobs
- Upload blobs
- Delete blobs
You'll run the code after you add all the snippets to the index.js file.
Declare fields for UI elements
Add the following code to the end of the index.js file.
const createContainerButton = document.getElementById("create-container-button");
const deleteContainerButton = document.getElementById("delete-container-button");
const selectButton = document.getElementById("select-button");
const fileInput = document.getElementById("file-input");
const listButton = document.getElementById("list-button");
const deleteButton = document.getElementById("delete-button");
const status = document.getElementById("status");
const fileList = document.getElementById("file-list");
const reportStatus = message => {
status.innerHTML += `${message}<br/>`;
status.scrollTop = status.scrollHeight;
}
Save the index.js file.
This code declares fields for each HTML element and implements a reportStatus function to display output.
In the following sections, add each new block of JavaScript code after the previous block.
Add your storage account info
Add code to access your storage account. Replace the placeholder with your Blob service SAS URL that you generated earlier. Add the following code to the end of the index.js file.
// Update <placeholder> with your Blob service SAS URL string
const blobSasUrl = "<placeholder>";
Save the index.js file.
Create client objects
Create BlobServiceClient and ContainerClient objects for interacting with the Azure Blob storage service. Add the following code to the end of the index.js file.
// Create a new BlobServiceClient
const blobServiceClient = new BlobServiceClient(blobSasUrl);
// Create a unique name for the container by
// appending the current time to the file name
const containerName = "container" + new Date().getTime();
// Get a container client from the BlobServiceClient
const containerClient = blobServiceClient.getContainerClient(containerName);
Save the index.js file.
Create and delete a storage container
Create and delete the storage container when you click the corresponding button on the web page. Add the following code to the end of the index.js file.
const createContainer = async () => {
try {
reportStatus(`Creating container "${containerName}"...`);
await containerClient.create();
reportStatus(`Done.`);
} catch (error) {
reportStatus(error.message);
}
};
const deleteContainer = async () => {
try {
reportStatus(`Deleting container "${containerName}"...`);
await containerClient.delete();
reportStatus(`Done.`);
} catch (error) {
reportStatus(error.message);
}
};
createContainerButton.addEventListener("click", createContainer);
deleteContainerButton.addEventListener("click", deleteContainer);
Save the index.js file.
List blobs
List the contents of the storage container when you click the List files button. Add the following code to the end of the index.js file.
const listFiles = async () => {
fileList.size = 0;
fileList.innerHTML = "";
try {
reportStatus("Retrieving file list...");
let iter = containerClient.listBlobsFlat();
let blobItem = await iter.next();
while (!blobItem.done) {
fileList.size += 1;
fileList.innerHTML += `<option>${blobItem.value.name}</option>`;
blobItem = await iter.next();
}
if (fileList.size > 0) {
reportStatus("Done.");
} else {
reportStatus("The container does not contain any files.");
}
} catch (error) {
reportStatus(error.message);
}
};
listButton.addEventListener("click", listFiles);
Save the index.js file.
This code calls the ContainerClient.listBlobsFlat function, then uses an iterator to retrieve the name of each BlobItem returned. For each BlobItem, it updates the Files list with the name property value.
Upload blobs
Upload files to the storage container when you click the Select and upload files button. Add the following code to the end of the index.js file.
const uploadFiles = async () => {
try {
reportStatus("Uploading files...");
const promises = [];
for (const file of fileInput.files) {
const blockBlobClient = containerClient.getBlockBlobClient(file.name);
promises.push(blockBlobClient.uploadBrowserData(file));
}
await Promise.all(promises);
reportStatus("Done.");
listFiles();
}
catch (error) {
reportStatus(error.message);
}
}
selectButton.addEventListener("click", () => fileInput.click());
fileInput.addEventListener("change", uploadFiles);
Save the index.js file.
This code connects the Select and upload files button to the hidden file-input element. The button click event triggers the file input click event and displays the file picker. After you select files and close the dialog box, the input event occurs and the uploadFiles function is called. This function creates a BlockBlobClient object, then calls the browser-only uploadBrowserData function for each file you selected. Each call returns a Promise. Each Promise is added to a list so that they can all be awaited together, causing the files to upload in parallel.
Delete blobs
Delete files from the storage container when you click the Delete selected files button. Add the following code to the end of the index.js file.
const deleteFiles = async () => {
try {
if (fileList.selectedOptions.length > 0) {
reportStatus("Deleting files...");
for (const option of fileList.selectedOptions) {
await containerClient.deleteBlob(option.text);
}
reportStatus("Done.");
listFiles();
} else {
reportStatus("No files selected.");
}
} catch (error) {
reportStatus(error.message);
}
};
deleteButton.addEventListener("click", deleteFiles);
Save the index.js file.
This code calls the ContainerClient.deleteBlob function to remove each file selected in the list. It then calls the listFiles function shown earlier to refresh the contents of the Files list.
Run the code
To run the code inside the Visual Studio Code debugger, configure the launch.json file for your browser.
Configure the debugger
To set up the debugger extension in Visual Studio Code:
- Select Run > Add Configuration
- Select Edge, Chrome, or Firefox, depending on which extension you installed in the Prerequisites section earlier.
Adding a new configuration creates a launch.json file and opens it in the editor. Modify the launch.json file so that the url value is http://localhost:1234/index.html, as shown here:
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "edge",
"request": "launch",
"name": "Launch Edge against localhost",
"url": "http://localhost:1234/index.html",
"webRoot": "${workspaceFolder}"
}
]
}
After updating, save the launch.json file. This configuration tells Visual Studio Code which browser to open and which URL to load.
Launch the web server
To launch the local development web server, select View > Terminal to open a console window inside Visual Studio Code, then enter the following command.
parcel index.html
Parcel bundles your code and starts a local development server for your page at http://localhost:1234/index.html. Changes you make to index.js will automatically be built and reflected on the development server whenever you save the file.
If you receive a message that says configured port 1234 could not be used, you can change the port by running the command parcel -p <port#> index.html. In the launch.json file, update the port in the URL path to match.
Start debugging
Run the page in the debugger and get a feel for how blob storage works. If any errors occur, the Status pane on the web page will display the error message received.
To open index.html in the browser with the Visual Studio Code debugger attached, select Run > Start Debugging or press F5 in Visual Studio Code.
Use the web app
In the Azure portal, you can verify the results of the API calls as you follow the steps below.
Step 1 - Create a container
- In the web app, select Create container. The status indicates that a container was created.
- To verify in the Azure portal, select your storage account. Under Blob service, select Containers. Verify that the new container appears. (You may need to select Refresh.)
Step 2 - Upload a blob to the container
- On your local computer, create and save a test file, such as test.txt.
- In the web app, click Select and upload files.
- Browse to your test file, and then select Open. The status indicates that the file was uploaded, and the file list was retrieved.
- In the Azure portal, select the name of the new container that you created earlier. Verify that the test file appears.
Step 3 - Delete the blob
- In the web app, under Files, select the test file.
- Select Delete selected files. The status indicates that the file was deleted and that the container contains no files.
- In the Azure portal, select Refresh. Verify that you see No blobs found.
Step 4 - Delete the container
- In the web app, select Delete container. The status indicates that the container was deleted.
- In the Azure portal, select the <account-name> | Containers link at the top-left of the portal pane.
- Select Refresh. The new container disappears.
- Close the web app.
Clean up resources
Click on the Terminal console in Visual Studio Code and press CTRL+C to stop the web server.
To clean up the resources created during this quickstart, go to the Azure portal and delete the resource group you created in the Prerequisites section.
Next steps
In this quickstart, you learned how to upload, list, and delete blobs using JavaScript. You also learned how to create and delete a blob storage container.
For tutorials, samples, quickstarts, and other documentation, visit:
- To learn more, see the Azure Blob storage client library for JavaScript.
- To see Blob storage sample apps, continue to Azure Blob storage client library v12 JavaScript samples.