Working with Azure Cosmos DB and JavaScript SDK
Last Updated :
28 Apr, 2025
Azure Cosmos DB is a No SQL database service that supports flexible schemas and hierarchical data for modern applications. It is a globally distributed, multi-model database service that supports document, key-value, wide-column, and graph databases. Azure Cosmos DB service takes care of database administration, updates, patching, and scaling. It also provides cost-effective serverless and automatic scaling options that match capacity with demand. Cosmos DB integrates with other Azure services and tools, such as Azure Functions, IoT Hub, AKS (Azure Kubernetes Service), App Service, and more. The Azure SDK for JavaScript is a collection of libraries that you can use to interact with various Azure services from your JavaScript applications. It supports both Node.js and browser environments.
In this article, we will learn about working with 'Azure Cosmos DB and the JavaScript SDK'. CRUD operations and other common operations on Azure Cosmos DB resources can be done using the JavaScript SDK. The Cosmos DB JavaScript SDK is primarily meant for use in Node.js applications.
To work with Azure Cosmos DB, the user needs to create the Cosmos DB by configuring it from the Azure Portal. If you already have an Azure Cosmos DB you can use it by following the steps after the 'creation of Azure Cosmos DB'. As a prerequisite, users need to have an Azure subscription.
Steps to Create Azure Azure Cosmos DB
Step 1: Login to Azure Portal Select the Create Cosmos DB option and select the 'Create' option
Step 2: Select the option 'Create' from the 'Azure Cosmos DB for NoSQL' blockStep 3: This screen shows options to select/input for the cosmos db to be created. Select Resource Group Name, Add a name , Select Location, and Click 'Review + Create

Step 4:Review and click 'Create'

Step 5:The Cosmos DB creation progress will be displayed and will display the database details once done.
Next Steps:
Select the database created.
- Add the Collection Name
- Add the Partition Key
- Create a new Document and add some data.
Example data:
{
"id": "1",
"category": "personal",
"name" : "groceries",
"description" : "Pick up apples and strawberries",
"isComplete" : false
}
In the data Explorer window of Azure Portal, from the 'Read-write Keys' tab, you can get the URI which will go to the 'endpoint' and the primary key value will go to the 'masterKey' .
Working With the JavaScript SDK
The Javascript SDK is a package that can be installed via npm to create,read,update and delete items in an Azure Cosmos DB container. It provides features and options to perform optimized queries to fetch data from documents in your database.
Install the required dependency for the Azure Cosmos DB for NoSQL JavaScript SDK using the below bash command.
npm install @azure/cosmos
Write the Javascript SDK scripts for connecting and working with Cosmos DB from Visual Studio Code Editor in a file called 'App.js'.Initially, CosmosClient class need to be created to interact with CosmosDB and then the required connection string details are added to access the Azure Cosmos DB. Once the connection is established, the script to fetch data and write it to console log is done using the iteration statement.
Node
const { CosmosClient } = require("@azure/cosmos");
const endpoint = "https://cosmosjohndatabase.documents.azure.com:443"; //Add the URI value
const masterkey = "<database account masterkey>"; // add the key value for the end point
const client = new CosmosClient({ endpoint, auth: {masterkey } });
const databaseId = "cosmosjohndatabase";
const containerId="cosmosjohncollection";
// Below is the code to connect to Cosmos DB and fetch data
async function main() {
const { result: results } = await client.database(databaseId).container(containerId).items.query(querySpec, { enableCrossPartitionQuery: true }).toArray();
//looping through data and writing to console
for (var queryResult of results){
let resultString = JSON.stringify(queryResult);
console.log('\tQuery returned ${resultString}\n);
}
}
main().catch((error) => {
console.error(error);
});
Once this code is run the resuts are printed in the console using the below command from Windows Powershell:
node App.js
Output

Best Practices For Working With Azure Cosmos Db
1. Choose The Appropriate Data Model And Right Api
- Use the appropriate data model (e.g., document, key-value, graph, column-family) based on your application's needs.
- Use the right APIs that best suits your application’s requirements and preferences. Azure Cosmos DB supports various APIs such as SQL API, MongoDB API, Cassandra API, Gremlin API, and Table API.
2. Choose The Best Consistency Level.
- Azure Cosmos DB offers five consistency levels such as: strong, bounded staleness, session, consistent prefix, and eventual.
- Choose the appropriate consistency level based on your application's requirements and trade-offs between consistency and performance.
3. Optimize The Partition Key To Improve Performance And Scalability.
- Azure Cosmos DB automatically partitions your data across multiple physical partitions based on the partition key you specify.
- A good partition key should have high cardinality, even distribution, and align with your query patterns.
4. Monitor And Tune Performance Regularly To Ensure Optimal Performance.
- Set up Cosmos DB diagnostic logs and metrics to monitor performance, errors, and resource usage.
- Integrate with Azure Monitor and Application Insights for advanced monitoring and alerting.
5. Implement Data Retention Policies And Archival Strategies To Manage Data Growth And Costs Effectively.
- Cosmos DB retention policy refers to how long and how often Azure Cosmos DB backs up your data.
- By default, Cosmos DB takes a full backup every 4 hours and retains the last 2 backups, which are free of charge.
- You can change the backup interval and retention period, but you will be charged extra for more than 2 backups.
- Utilize time-to-live (TTL) settings for automatic data expiration.
6. Multi-Region Data Distribution (Geo-Replication) And Multi-Region Writes (Multi-Master)
- Azure Cosmos DB can replicate and distribute your data to any or all Azure regions.
- Single region Azure Cosmos DB accounts have guaranteed 99.99% availability and adding additional regions to your Azure Cosmos DB account can further improve availability.
- Adding additional regions also helps lower latency by placing data physically closer to your users.
7. Use The.Net Sdk To Manage Azure Cosmos Db Resources.
- The.NET SDK provides a convenient way to interact with Azure Cosmos DB from your.NET applications.
- Azure SDKs for Cosmos DB are optimized for your programming language to simplify development and improve performance.
- You can use the SDK to create, read, update, and delete items in an Azure Cosmos DB container.
8. Performance & Cost Optimization
- When you created your new account, you had to choose the database operations pricing model that best meets the requirements of the application or workload.
- Select the best option between the provisioned throughput and serverless models.
These are the few best practices listed above. Backup and Disaster Recovery, Cost Management, Capacity Planning, Security and Query Optimization are some of the other best practices recommended.
Troubleshooting Common Azure Cosmos Db Problems
Here are some common issues you might encounter and steps to help resolve them:
1. Connection And Authentication Errors
Issue: Difficulty connecting to Azure Cosmos DB due to network problems or authentication errors.
Troubleshooting:
- Check your network connectivity and ensure that your firewall rules allow access to Cosmos DB.
- Verify that your authentication credentials, such as the endpoint and access key or resource token, are correct.
- If using Azure AD authentication, make sure it is correctly configured and permissions are granted.
2. High Request Unit (RU) Consumption
Issue: Unexpectedly high RU consumption, leading to increased costs.
Troubleshooting:
- Use the Query Explorer in the Azure Portal or diagnostic logs to identify and optimize inefficient queries.
- Implement correct indexing for frequently used queries.
- Consider enabling and reviewing the Query Metrics in the Azure Portal for insights into query performance.
3. Query Timeout Errors
Issue: Queries timing out or taking too long to execute.
Troubleshooting:
- Optimize queries that frequently time out by indexing, using the right partition key, or increasing RU limits.
- Adjust the client application's timeout settings to allow for longer query execution times if necessary.
4. Resource Exhaustion
Issue: Running out of resources such as throughput, CPU, or memory.
Troubleshooting:
- Monitor resource utilization, including CPU and memory, using Azure Monitor and scale your Cosmos DB container or throughput provision as needed.
- Consider using autoscale to automatically adjust resources based on demand.
5. Resource Exhaustion
Issue: Running out of resources such as throughput, CPU, or memory.
Troubleshooting:
- Monitor resource utilization, including CPU and memory, and scale your Cosmos DB container or throughput provision as needed.
- Consider using autoscale to automatically adjust resources based on demand.
6. Client-Side Errors and Exceptions
Issue: Client applications encountering errors or exceptions when interacting with Cosmos DB.
Troubleshooting:
- Implement proper error handling mechanisms in your JavaScript application, including try-catch blocks or promises.
- Review and address error messages and codes provided by the SDK for specific issues.
- Enable diagnostic logging and monitor logs for any unusual behavior or error messages.
When troubleshooting Cosmos DB issues, it's important to gather as much information as possible, including error messages, logs, and performance metrics. Azure's monitoring and diagnostic tools can be invaluable for identifying and resolving problems quickly.
Similar Reads
API In Azure Cosmos DB Azure Cosmos DB, a multi-model database service provided globally by Microsoft, allows users to increase the storage and throughput across multiple locations elastically and autonomously. Azure Cosmos DB provides native support for several data formats, including document, key-value, graph, and colu
10 min read
What is Partition Key In Azure Cosmos DB The Partition Key in Azure Cosmos DB is an important factor for distributing data efficiently across the database's physical partitions. The partition key plays an important role in storing and accessing data and the partition key makes the filtering data more efficient and optimized. In this articl
7 min read
How to Setup Azure Cosmos DB? Azure Cosmos DB is a managed database service that provides high availability and scalability to applications. It provides support for various NoSQL databases. It is available in cross regions hence providing high throughput. In this article, we will set up Azure cosmos DB for NoSQL. So let's see ho
3 min read
Introduction to Azure Cosmos DB CosmosDB is a NoSQL database by Azure. In this article, We'll discuss high-level horizontal scaling, replication, partitioning, and database schema. And then we'll dive into some of the data models that Cosmos DB supports. So, let's get started. Applications used to be relatively simple. We would ha
5 min read
Microsoft Azure - Choosing a Partition Key in Cosmos DB Azure Cosmos DB makes use of partitioning to scale individual containers in a database subsequently enhancing the performance needs of your application. In partitioning, the items in a container are divided into distinct subsets called logical partitions. Logical partitions are created based on the
3 min read
Microsoft Azure - Notebooks in Cosmos DB In this article we will learn about how to use Azure Cosmos DB built-in notebooks. So, the easiest way to get started is from the data explorer. You can go to the gallery tab, and so you have official samples written by the Cosmos DB team as well as samples submitted by users in the public gallery.
5 min read
Microsoft Azure - Using C# in CosmoDB In this article, we will look into how to use C# notebooks in Azure Cosmos DB. When you are creating an application that uses Azure Cosmos DB, it is useful to experiment with code that uses that Cosmos DB. In Azure Cosmos DB, you can use C# notebooks that enable you to write the C# code that interac
3 min read
Introduction to Azure Cosmos DB for Apache Gremlin Pre-requisite: Microsoft Cosmos DB Microsoft offers Azure Cosmos DB, a multi-model, globally distributed database service. It is the first cloud database to offer comprehensive support for the Apache Gremlin graph API, making it the perfect choice for developers who want to build highly-scalable and
8 min read
Microsoft Azure - Build and Deploy App with Azure SDK For Java In this article, we will learn how to build and deploy our first app with the Azure SDK for Java. We can run almost any type of application in Azure including Java applications. The Azure SDKs are collections of libraries built to make it easier to use Azure services from your language of choice. Th
3 min read
How to Use Azure Monitor to Observe and Diagnose a JavaScript Error? JavaScript is a very versatile language but still errors can occur, main to sudden conduct and personal dissatisfaction. Microsoft Azure offers an effective device referred to as Azure Monitor, which allows developers to identify, look at, and diagnose JavaScript errors effectively. In this text, we
7 min read