Azure Cosmos DB for NoSQL in Node.js: @azure/cosmos with identity
The @azure/cosmos CosmosClient takes endpoint + key or an Entra credential. Same data-role requirement; the JS traps are the resource-token API and forgotten partition keys.
import { CosmosClient } from "@azure/cosmos";
import { DefaultAzureCredential } from "@azure/identity";
const client = new CosmosClient({
endpoint: "https://YOUR-ACCOUNT.documents.azure.com:443/",
aadCredentials: new DefaultAzureCredential(),
});
const { database } = await client.databases.createIfNotExists({ id: "[db]" });
const { container } = await database.containers.createIfNotExists({
id: "[container]",
partitionKey: "/tenantId",
});Traps:
- aadCredentials, not credential. The option name in @azure/cosmos is
aadCredentials. Passingcredentialsilently does nothing and you get auth errors. - Data-plane role. "Cosmos DB Built-in Data Contributor" via
az cosmosdb sql role assignment create. Same 403-without-it story. - createIfNotExists is your friend. Databases and containers: create-if-not-exists in setup code avoids 404/409 races in fresh environments.
- Partition key on every write. Point operations need both id and partition key value. Forgetting the partition key value on
container.item(id, pk).read()is the classic 404-that-is-not-a-404.
Verify: write one item, point-read it back, then run a query and log the request charge.
Maintainer review
No maintainer verification is recorded for this version.
This records the version a maintainer checked. It does not assert that the version is the latest upstream release.