Azure Cosmos DB Quickstart

← Back to Cosmos DB docs

What you’ll build

In this quickstart you will create an Azure Cosmos DB account, a container, and a simple Node.js application that performs CRUD operations using the SQL API.

Prerequisites

  • Azure subscription (free trial works)
  • Node.js v18+ installed
  • Git installed
  • Visual Studio Code (optional)

Step 1 – Create a Cosmos DB account

  1. Open the Azure portal and click Create a resource.
  2. Search for Azure Cosmos DB and select Azure Cosmos DB for NoSQL.
  3. Configure:
    • Account Name: quickstart-cosmos-db
    • Subscription: Your subscription
    • Resource Group: quickstart-rg (create new)
    • Location: Choose a region close to you
  4. Click Review + create then Create.

Step 2 – Create a database and container

  1. Navigate to your newly created Cosmos DB account.
  2. In the left menu select Data ExplorerNew Container.
  3. Enter:
    • Database id: QuickstartDB
    • Container id: Items
    • Partition key: /id
  4. Click OK.

Step 3 – Get the connection string

  1. In the Cosmos DB account blade, select Keys.
  2. Copy the PRIMARY CONNECTION STRING.

Step 4 – Build the Node.js app

Open a terminal and run:

git clone https://github.com/Azure/azure-cosmos-js-getting-started.git
cd azure-cosmos-js-getting-started
npm install
      

Replace the placeholder in .env with your connection string:

COSMOS_CONNECTION_STRING=YOUR_CONNECTION_STRING_HERE
      

Run the app:

node index.js
      

Sample Code (index.js)

require('dotenv').config();
const { CosmosClient } = require("@azure/cosmos");

const endpoint = process.env.COSMOS_ENDPOINT;
const key = process.env.COSMOS_KEY;
const client = new CosmosClient({ endpoint, key });

async function run() {
  const database = client.database("QuickstartDB");
  const container = database.container("Items");

  // Create an item
  const newItem = { id: "item1", name: "Sample Item", description: "First item" };
  await container.items.create(newItem);
  console.log("Item created");

  // Read the item
  const { resource } = await container.item(newItem.id).read();
  console.log("Read item:", resource);

  // Update the item
  resource.description = "Updated description";
  await container.item(resource.id).replace(resource);
  console.log("Item updated");

  // Delete the item
  await container.item(resource.id).delete();
  console.log("Item deleted");
}

run().catch(err => console.error(err));