Get started with Azure Blob Storage and JavaScript
This article shows you how to connect to Azure Blob Storage by using the Azure Blob Storage client library v12 for JavaScript. Once connected, your code can operate on containers, blobs, and features of the Blob Storage service.
The sample code snippets are available in GitHub as runnable Node.js files.
Package (npm) | Samples | API reference | Library source code | Give Feedback
SDK Objects for service, container, and blob
The BlobServiceClient object is the top object in the SDK. This client allows you to manipulate the service, containers and blobs. From the BlobServiceClient, you can get to the ContainerClient. The ContainerClient object allows you to interact with a container and its blobs. The BlobClient allows you to manipulate blobs.
| Client | Allows access to | Accessed |
|---|---|---|
| Account: BlobServiceClient | Controls your service resource, provides access to container and blobs. | Directly from SDK via require statement. |
| Container: ContainerClient | Controls a specific container, provides access to blobs. | Directly from SDK via require statement or from BlobServiceClient. |
| Blob: BlobClient | Access to a blob of any kind: block, append, page. | Directly from SDK via require statement or from ContainerClient. |

Prerequisites
- Azure subscription - create one for free
- Azure storage account - create a storage account
- Node.js LTS
- Optionally, you need bundling tools if you're developing for a web client.
Set up your project
Open a command prompt and change into your project folder. Change
YOUR-DIRECTORYto your folder name:cd YOUR-DIRECTORYIf you don't have a
package.jsonfile already in your directory, initialize the project to create the file:npm init -yInstall the Azure Blob Storage client library for JavaScript:
npm install @azure/storage-blobIf you want to connect with managed identity, install the Azure Identity client library for JavaScript:
npm install @azure/identity
Authenticate to Azure with passwordless credential
Azure Active Directory (Azure AD) provides the most secure connection by managing the connection identity (managed identity). This passwordless functionality allows you to develop an application that doesn't require any secrets (keys or connection strings) stored in the code.
Set up identity access to the Azure cloud
To connect to Azure without passwords, you need to set up an Azure identity or use an existing identity. Once the identity is set up, make sure to assign the appropriate roles to the identity.
To authorize passwordless access with Azure AD, you'll need to use an Azure credential. Which type of credential you need depends on where your application runs. Use this table as a guide.
| Environment | Method |
|---|---|
| Developer environment | Visual Studio Code |
| Developer environment | Service principal |
| Azure-hosted apps | Azure-hosted apps setup |
| On-premises | On-premises app setup |
Set up storage account roles
Your storage resource needs to have one or more of the following Azure RBAC roles assigned to the identity resource you plan to connect with. Setup the Azure Storage roles for each identity you created in the previous step: Azure cloud, local development, on-premises.
After you complete the setup, each identity needs at least one of the appropriate roles:
- A data access role - such as:
- Storage Blob Data Reader
- Storage Blob Data Contributor
- A resource role - such as:
- Reader
- Contributor
Connect with passwordless authentication to Azure
Once your Azure storage account identity roles and your local environment are set up, create a JavaScript file which includes the @azure/identity package. Using the DefaultAzureCredential class provided by the Azure.Identity client library is the recommended approach for implementing passwordless connections to Azure services in your code, including Blob Storage.
Create a DefaultAzureCredential instance. Use that object to create a BlobServiceClient.
// connect-with-default-azure-credential.js
const { BlobServiceClient } = require('@azure/storage-blob');
const { DefaultAzureCredential } = require('@azure/identity');
require('dotenv').config()
const accountName = process.env.AZURE_STORAGE_ACCOUNT_NAME;
if (!accountName) throw Error('Azure Storage accountName not found');
const blobServiceClient = new BlobServiceClient(
`https://${accountName}.blob.core.windows.net`,
new DefaultAzureCredential()
);
async function main(){
const containerName = 'REPLACE-WITH-EXISTING-CONTAINER-NAME';
const blobName = 'REPLACE-WITH-EXISTING-BLOB-NAME';
const timestamp = Date.now();
const fileName = `my-new-file-${timestamp}.txt`;
// create container client
const containerClient = await blobServiceClient.getContainerClient(containerName);
// create blob client
const blobClient = await containerClient.getBlockBlobClient(blobName);
// download file
await blobClient.downloadToFile(fileName);
console.log(`${fileName} downloaded`);
}
main()
.then(() => console.log(`done`))
.catch((ex) => console.log(`error: ${ex.message}`));
The dotenv package is used to read your storage account name from a .env file. This file should not be checked into source control. If you use a local service principal as part of your DefaultAzureCredential set up, any security information for that credential will also go into the .env file.
If you plan to deploy the application to servers and clients that run outside of Azure, you can obtain an OAuth token by using other classes in the Azure Identity client library for JavaScript which derive from the TokenCredential class.
Connect with an account name and key
Create a StorageSharedKeyCredential by using the storage account name and account key. Then use the StorageSharedKeyCredential to initialize a BlobServiceClient.
// connect-with-account-name-and-key.js
const { BlobServiceClient, StorageSharedKeyCredential } = require('@azure/storage-blob');
require('dotenv').config()
const accountName = process.env.AZURE_STORAGE_ACCOUNT_NAME;
const accountKey = process.env.AZURE_STORAGE_ACCOUNT_KEY;
if (!accountName) throw Error('Azure Storage accountName not found');
if (!accountKey) throw Error('Azure Storage accountKey not found');
const sharedKeyCredential = new StorageSharedKeyCredential(accountName, accountKey);
const blobServiceClient = new BlobServiceClient(
`https://${accountName}.blob.core.windows.net`,
sharedKeyCredential
);
async function main() {
const containerName = 'REPLACE-WITH-EXISTING-CONTAINER-NAME';
const blobName = 'REPLACE-WITH-EXISTING-BLOB-NAME';
const timestamp = Date.now();
const fileName = `my-new-file-${timestamp}.txt`;
// create container client
const containerClient = await blobServiceClient.getContainerClient(containerName);
// create blob client
const blobClient = await containerClient.getBlockBlobClient(blobName);
// download file
await blobClient.downloadToFile(fileName);
console.log(`${fileName} downloaded`);
}
main()
.then(() => console.log(`done`))
.catch((ex) => console.log(ex.message));
The dotenv package is used to read your storage account name and key from a .env file. This file should not be checked into source control.
For information about how to obtain account keys and best practice guidelines for properly managing and safeguarding your keys, see Manage storage account access keys.
Connect with a connection string
Create a BlobServiceClient by using a connection string.
// connect-with-connection-string.js
const { BlobServiceClient } = require('@azure/storage-blob');
require('dotenv').config()
const connString = process.env.AZURE_STORAGE_CONNECTION_STRING;
if (!connString) throw Error('Azure Storage Connection string not found');
const blobServiceClient = BlobServiceClient.fromConnectionString(connString);
async function main(){
const containerName = 'REPLACE-WITH-EXISTING-CONTAINER-NAME';
const blobName = 'REPLACE-WITH-EXISTING-BLOB-NAME';
const timestamp = Date.now();
const fileName = `my-new-file-${timestamp}.txt`;
// create container client
const containerClient = await blobServiceClient.getContainerClient(containerName);
// create blob client
const blobClient = await containerClient.getBlockBlobClient(blobName);
// download file
await blobClient.downloadToFile(fileName);
console.log(`${fileName} downloaded`);
}
main()
.then(() => console.log(`done`))
.catch((ex) => console.log(ex.message));
The dotenv package is used to read your storage account connection string from a .env file. This file should not be checked into source control.
For information about how to obtain account keys and best practice guidelines for properly managing and safeguarding your keys, see Manage storage account access keys.
Connect with a SAS token
Create a Uri to your resource by using the blob service endpoint and SAS token. Then, create a BlobServiceClient with the Uri.
// connect-with-sas-token.js
const { BlobServiceClient } = require('@azure/storage-blob');
require('dotenv').config()
const accountName = process.env.AZURE_STORAGE_ACCOUNT_NAME;
const sasToken = process.env.AZURE_STORAGE_SAS_TOKEN;
if (!accountName) throw Error('Azure Storage accountName not found');
if (!sasToken) throw Error('Azure Storage accountKey not found');
const blobServiceUri = `https://${accountName}.blob.core.windows.net`;
const blobServiceClient = new BlobServiceClient(
`${blobServiceUri}${sasToken}`,
null
);
async function main(){
const containerName = 'REPLACE-WITH-EXISTING-CONTAINER-NAME';
const blobName = 'REPLACE-WITH-EXISTING-BLOB-NAME';
const timestamp = Date.now();
const fileName = `my-new-file-${timestamp}.txt`;
// create container client
const containerClient = await blobServiceClient.getContainerClient(containerName);
// create blob client
const blobClient = await containerClient.getBlockBlobClient(blobName);
// download file
await blobClient.downloadToFile(fileName);
console.log(`${fileName} downloaded`);
}
main()
.then(() => console.log(`done`))
.catch((ex) => console.log(`error: ${ex.message}`));
The dotenv package is used to read your storage account name and sas token from a .env file. This file should not be checked into source control.
To generate and manage SAS tokens, see any of these articles:
Connect anonymously
If you explicitly enable anonymous access, then you can connect to Blob Storage without authorization for your request. You can create a new BlobServiceClient object for anonymous access by providing the Blob storage endpoint for the account. This requires you to know the account and container names. To learn how to enable anonymous access, see Configure anonymous public read access for containers and blobs.
// connect-with-anonymous-credential.js
const { BlobServiceClient, AnonymousCredential } = require('@azure/storage-blob');
require('dotenv').config()
const accountName = process.env.AZURE_STORAGE_ACCOUNT_NAME;
if (!accountName) throw Error('Azure Storage accountName not found');
const blobServiceUri = `https://${accountName}.blob.core.windows.net`;
const blobServiceClient = new BlobServiceClient(
blobServiceUri,
new AnonymousCredential()
);
async function getContainerProperties(){
const containerName = 'REPLACE-WITH-EXISTING-CONTAINER-NAME';
const blobName = 'REPLACE-WITH-EXISTING-BLOB-NAME';
const timestamp = Date.now();
const fileName = `my-new-file-${timestamp}.txt`;
// create container client
const containerClient = await blobServiceClient.getContainerClient(containerName);
// create blob client
const blobClient = await containerClient.getBlockBlobClient(blobName);
// download file
await blobClient.downloadToFile(fileName);
console.log(`${fileName} downloaded`);
}
getContainerProperties()
.then(() => console.log(`done`))
.catch((ex) => console.log(`error: ${ex.message}`));
The dotenv package is used to read your storage account name from a .env file. This file should not be checked into source control.
Each type of resource is represented by one or more associated JavaScript clients:
| Class | Description |
|---|---|
| BlobServiceClient | Represents the Blob Storage endpoint for your storage account. |
| ContainerClient | Allows you to manipulate Azure Storage containers and their blobs. |
| BlobClient | Allows you to manipulate Azure Storage blobs. |
The following guides show you how to use each of these clients to build your application. The sample code shown is this guide is available on GitHub.
| Guide | Description |
|---|---|
| Create a container | Create containers. |
| Get container's URL | Get URL of container. |
| Delete and restore containers | Delete containers, and if soft-delete is enabled, restore deleted containers. |
| List containers | List containers in an account and the various options available to customize a listing. |
| Manage properties and metadata | Get and set properties and metadata for containers. |
| Upload blobs | Learn how to upload blobs by using strings, streams, file paths, and other methods. |
| Get blob's URL | Get URL of blob. |
| Download blobs | Download blobs by using strings, streams, and file paths. |
| Copy blobs | Copy a blob from one account to another account. |
| List blobs | List blobs in different ways. |
| Delete and restore | Delete blobs, and if soft-delete is enabled, restore deleted blobs. |
| Find blobs using tags | Set and retrieve indexed tags then use tags to find blobs. |
| Manage properties and metadata | Get all system properties and set HTTP properties and metadata for blobs. |
See also
Feedback
Submit and view feedback for