Get started with Azure Cosmos DB for NoSQL using JavaScript
APPLIES TO: NoSQL
This article shows you how to connect to Azure Cosmos DB for NoSQL using the JavaScript SDK. Once connected, you can perform operations on databases, containers, and items.
Package (npm) | Samples | API reference | Library source code | Give Feedback
Prerequisites
- An Azure account with an active subscription. Create an account for free.
- Azure Cosmos DB for NoSQL account. Create a API for NoSQL account.
- Node.js LTS
- Azure Command-Line Interface (CLI) or Azure PowerShell
Set up your local project
Create a new directory for your JavaScript project in a bash shell.
mkdir cosmos-db-nosql-javascript-samples && cd ./cosmos-db-nosql-javascript-samples
Create a new JavaScript application by using the
npm init
command with the console template.npm init -y
Install the required dependency for the Azure Cosmos DB for NoSQL JavaScript SDK.
npm install @azure/cosmos
Connect to Azure Cosmos DB for NoSQL
To connect to the API for NoSQL of Azure Cosmos DB, create an instance of the CosmosClient
class. This class is the starting point to perform all operations against databases. There are three core ways to connect to an API for NoSQL account using the CosmosClient class:
- Connect with a API for NoSQL endpoint and read/write key
- Connect with a API for NoSQL connection string
- Connect with Microsoft Entra ID
Connect with an endpoint and key
The most common constructor for CosmosClient has two parameters:
Parameter | Example value | Description |
---|---|---|
accountEndpoint |
COSMOS_ENDPOINT environment variable |
API for NoSQL endpoint to use for all requests |
authKeyOrResourceToken |
COSMOS_KEY environment variable |
Account key or resource token to use when authenticating |
Retrieve your account endpoint and key
Create a shell variable for resourceGroupName.
# Variable for resource group name resourceGroupName="msdocs-cosmos-javascript-howto-rg"
Use the
az cosmosdb list
command to retrieve the name of the first Azure Cosmos DB account in your resource group and store it in the accountName shell variable.# Retrieve most recently created account name accountName=$( az cosmosdb list \ --resource-group $resourceGroupName \ --query "[0].name" \ --output tsv )
Get the API for NoSQL endpoint URI for the account using the
az cosmosdb show
command.az cosmosdb show \ --resource-group $resourceGroupName \ --name $accountName \ --query "documentEndpoint"
Find the PRIMARY KEY from the list of keys for the account with the
az-cosmosdb-keys-list
command.az cosmosdb keys list \ --resource-group $resourceGroupName \ --name $accountName \ --type "keys" \ --query "primaryMasterKey"
Record the URI and PRIMARY KEY values. You'll use these credentials later.
To use the URI and PRIMARY KEY values within your code, persist them to new environment variables on the local machine running the application.
$env:COSMOS_ENDPOINT = "<cosmos-account-URI>"
$env:COSMOS_KEY = "<cosmos-account-PRIMARY-KEY>"
Create CosmosClient with account endpoint and key
Create a new instance of the CosmosClient class with the COSMOS_ENDPOINT
and COSMOS_KEY
environment variables as parameters.
const client = new CosmosClient({ endpoint, key });
Connect with a connection string
Another constructor for CosmosClient only contains a single parameter:
Parameter | Example value | Description |
---|---|---|
accountEndpoint |
COSMOS_ENDPOINT environment variable |
API for NoSQL endpoint to use for all requests |
connectionString |
COSMOS_CONNECTION_STRING environment variable |
Connection string to the API for NoSQL account |
Retrieve your account connection string
Use the
az cosmosdb list
command to retrieve the name of the first Azure Cosmos DB account in your resource group and store it in the accountName shell variable.# Retrieve most recently created account name accountName=$( az cosmosdb list \ --resource-group $resourceGroupName \ --query "[0].name" \ --output tsv )
Find the PRIMARY CONNECTION STRING from the list of connection strings for the account with the
az-cosmosdb-keys-list
command.az cosmosdb keys list \ --resource-group $resourceGroupName \ --name $accountName \ --type "connection-strings" \ --query "connectionStrings[?description == \`Primary SQL Connection String\`] | [0].connectionString"
To use the PRIMARY CONNECTION STRING value within your code, persist it to a new environment variable on the local machine running the application.
$env:COSMOS_CONNECTION_STRING = "<cosmos-account-PRIMARY-CONNECTION-STRING>"
Create CosmosClient with connection string
Create a new instance of the CosmosClient class with the COSMOS_CONNECTION_STRING
environment variable as the only parameter.
// New instance of CosmosClient class using a connection string
const cosmosClient = new CosmosClient(process.env.COSMOS_CONNECTION_STRING);
Connect using the Microsoft identity platform
To connect to your API for NoSQL account using the Microsoft identity platform and Microsoft Entra ID, use a security principal. The exact type of principal depends on where you host your application code. The table below serves as a quick reference guide.
Where the application runs | Security principal |
---|---|
Local machine (developing and testing) | User identity or service principal |
Azure | Managed identity |
Servers or clients outside of Azure | Service principal |
Import @azure/identity
The @azure/identity npm package contains core authentication functionality that is shared among all Azure SDK libraries.
Import the @azure/identity npm package using the
npm install
command.npm install @azure/identity
In your code editor, add the dependencies.
const { DefaultAzureCredential } = require("@azure/identity");
Create CosmosClient with default credential implementation
If you're testing on a local machine, or your application will run on Azure services with direct support for managed identities, obtain an OAuth token by creating a DefaultAzureCredential
instance. Then create a new instance of the CosmosClient class with the COSMOS_ENDPOINT
environment variable and the TokenCredential object as parameters.
const { CosmosClient } = require("@azure/cosmos");
const { DefaultAzureCredential } = require("@azure/identity");
const credential = new DefaultAzureCredential();
const cosmosClient = new CosmosClient({
endpoint,
aadCredentials: credential
});
Create CosmosClient with a custom credential implementation
If you plan to deploy the application out of Azure, you can obtain an OAuth token by using other classes in the @azure/identity client library for JavaScript. These other classes also derive from the TokenCredential
class.
For this example, we create a ClientSecretCredential
instance by using client and tenant identifiers, along with a client secret.
You can obtain the client ID, tenant ID, and client secret when you register an application in Microsoft Entra ID. For more information about registering Microsoft Entra applications, see Register an application with the Microsoft identity platform.
Create a new instance of the CosmosClient class with the COSMOS_ENDPOINT
environment variable and the TokenCredential object as parameters.
const { CosmosClient } = require("@azure/cosmos");
const { DefaultAzureCredential } = require("@azure/identity");
const credential = new ClientSecretCredential(
tenantId: process.env.AAD_TENANT_ID,
clientId: process.env.AAD_CLIENT_ID,
clientSecret: process.env.AAD_CLIENT_SECRET
);
const cosmosClient = new CosmosClient({
endpoint,
aadCredentials: credential
});
Build your application
As you build your application, your code will primarily interact with four types of resources:
The API for NoSQL account, which is the unique top-level namespace for your Azure Cosmos DB data.
Databases, which organize the containers in your account.
Containers, which contain a set of individual items in your database.
Items, which represent a JSON document in your container.
The following diagram shows the relationship between these resources.
Hierarchical diagram showing an Azure Cosmos DB account at the top. The account has two child database nodes. One of the database nodes includes two child container nodes. The other database node includes a single child container node. That single container node has three child item nodes.
Each type of resource is represented by one or more associated classes. Here's a list of the most common classes:
Class | Description |
---|---|
CosmosClient |
This class provides a client-side logical representation for the Azure Cosmos DB service. The client object is used to configure and execute requests against the service. |
Database |
This class is a reference to a database that may, or may not, exist in the service yet. The database is validated server-side when you attempt to access it or perform an operation against it. |
Container |
This class is a reference to a container that also may not exist in the service yet. The container is validated server-side when you attempt to work with it. |
The following guides show you how to use each of these classes to build your application.
Guide | Description |
---|---|
Create a database | Create databases |
Create a container | Create containers |
Create and read an item | Point read a specific item |
Query items | Query multiple items |
See also
Next steps
Now that you've connected to an API for NoSQL account, use the next guide to create and manage databases.
Feedback
https://aka.ms/ContentUserFeedback.
Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see:Submit and view feedback for