Tutorial: Connect a Node.js web app with Azure Cosmos DB for MongoDB (vCore)

APPLIES TO: MongoDB vCore

In this tutorial, you build a Node.js web application that connects to Azure Cosmos DB for MongoDB in vCore architecture. The MongoDB, Express, React.js, Node.js (MERN) stack is a popular collection of technologies used to build many modern web applications. With Azure Cosmos DB for MongoDB (vCore), you can build a new web application or migrate an existing application using MongoDB drivers that you're already familiar with. In this tutorial, you:

  • Set up your environment
  • Test the MERN application with a local MongoDB container
  • Test the MERN application with a vCore cluster
  • Deploy the MERN application to Azure App Service

Prerequisites

To complete this tutorial, you need the following resources:

  • An existing vCore cluster.
  • A GitHub account.
    • GitHub comes with free Codespaces hours for all users.

Configure development environment

A development container environment is available with all dependencies required to complete every exercise in this project. You can run the development container in GitHub Codespaces or locally using Visual Studio Code.

GitHub Codespaces runs a development container managed by GitHub with Visual Studio Code for the Web as the user interface. For the most straightforward development environment, use GitHub Codespaces so that you have the correct developer tools and dependencies preinstalled to complete this training module.

Important

All GitHub accounts can use Codespaces for up to 60 hours free each month with 2 core instances.

  1. Start the process to create a new GitHub Codespace on the main branch of the azure-samples/msdocs-azure-cosmos-db-mongodb-mern-web-app GitHub repository.

    Open in GitHub Codespaces

  2. On the Create codespace page, review the codespace configuration settings and then select Create new codespace

    Screenshot of the confirmation screen before creating a new codespace.

  3. Wait for the codespace to start. This startup process can take a few minutes.

  4. Open a new terminal in the codespace.

    Tip

    You can use the main menu to navigate to the Terminal menu option and then select the New Terminal option.

    Screenshot of the codespaces menu option to open a new terminal.

  5. Check the versions of the tools you use in this tutorial.

    docker --version
    
    node --version
    
    npm --version
    
    az --version
    

    Note

    This tutorial requires the following versions of each tool which are preinstalled in your environment:

    Tool Version
    Docker ≥ 20.10.0
    Node.js ≥ 18.0150
    NPM ≥ 9.5.0
    Azure CLI ≥ 2.46.0
  6. Close the terminal.

  7. The remaining steps in this tutorial take place in the context of this development container.

Test the MERN application's API with the MongoDB container

Start by running the sample application's API with the local MongoDB container to validate that the application works.

  1. Run a MongoDB container using Docker and publish the typical MongoDB port (27017).

    docker pull mongo:6.0
    
    docker run --detach --publish 27017:27017 mongo:6.0
    
  2. In the side bar, select the MongoDB extension.

    Screenshot of the MongoDB extension in the side bar.

  3. Add a new connection to the MongoDB extension using the connection string mongodb://localhost.

    Screenshot of the add connection button in the MongoDB extension.

  4. Once the connection is successful, open the data/products.mongodb playground file.

  5. Select the Run all icon to execute the script.

    Screenshot of the run all button in a playground for the MongoDB extension.

  6. The playground run should result in a list of documents in the local MongoDB collection. Here's a truncated example of the output.

    [
      {
        "_id": { "$oid": "640a146e89286b79b6628eef" },
        "name": "Confira Watch",
        "category": "watches",
        "price": 105
      },
      {
        "_id": { "$oid": "640a146e89286b79b6628ef0" },
        "name": "Diannis Watch",
        "category": "watches",
        "price": 98,
        "sale": true
      },
      ...
    ]
    

    Note

    The object ids (_id) are randomnly generated and will differ from this truncated example output.

  7. In the server/ directory, create a new .env file.

  8. In the server/.env file, add an environment variable for this value:

    Environment Variable Value
    CONNECTION_STRING The connection string to the Azure Cosmos DB for MongoDB (vCore) cluster. For now, use mongodb://localhost:27017?directConnection=true.
    CONNECTION_STRING=mongodb://localhost:27017?directConnection=true
    
  9. Change the context of the terminal to the server/ folder.

    cd server
    
  10. Install the dependencies from Node Package Manager (npm).

    npm install
    
  11. Start the Node.js & Express application.

    npm start
    
  12. The API automatically opens a browser window to verify that it returns an array of product documents.

  13. Close the extra browser tab/window.

  14. Close the terminal.

Test the MERN application with the Azure Cosmos DB for MongoDB (vCore) cluster

Now, let's validate that the application works seamlessly with Azure Cosmos DB for MongoDB (vCore). For this task, populate the pre-existing cluster with seed data using the MongoDB shell and then update the API's connection string.

  1. Sign in to the Azure portal (https://portal.azure.cn).

  2. Navigate to the existing Azure Cosmos DB for MongoDB (vCore) cluster page.

  3. From the Azure Cosmos DB for MongoDB (vCore) cluster page, select the Connection strings navigation menu option.

    Screenshot of the connection strings option on the page for a cluster.

  4. Record the value from the Connection string field.

    Screenshot of the connection string credential for a cluster.

    Important

    The connection string in the portal does not include the username and password values. You must replace the <user> and <password> placeholders with the credentials you used when you originally created the cluster.

  5. Back within your integrated development environment (IDE), open a new terminal.

  6. Start the MongoDB Shell using the mongosh command and the connection string you recorded earlier. Make sure you replace the <user> and <password> placeholders with the credentials you used when you originally created the cluster.

    mongosh "<mongodb-cluster-connection-string>"
    

    Note

    You may need to encode specific values for the connection string. In this example, the name of the cluster is msdocs-cosmos-tutorial, the username is clusteradmin, and the password is P@ssw.rd. In the password the @ character will need to be encoded using %40. An example connection string is provided here with the correct encoding of the password.

    CONNECTION_STRING=mongodb+srv://clusteradmin:P%40ssw.rd@msdocs-cosmos-tutorial.mongocluster.cosmos.azure.cn/?tls=true&authMechanism=SCRAM-SHA-256&retrywrites=false&maxIdleTimeMS=120000
    
  7. Within the shell, run the following commands to create your database, create your collection, and seed with starter data.

use('cosmicworks');

db.products.drop();

db.products.insertMany([
  { name: "Confira Watch", category: "watches", price: 105.00 },
  { name: "Diannis Watch", category: "watches", price: 98.00, sale: true },
  { name: "Sterse Gloves", category: "gloves", price: 42.00 },
  { name: "Peache Sunglasses", category: "eyewear", price: 32.00, sale: false, sizes: [ "S", "M", "L" ] },
  { name: "Icento Pack", category: "bags", price: 58.00 },
  { name: "Iroowl Bracelet", category: "watches", price: 66.00 },
  { name: "Glaark Bag", category: "bags", price: 56.00, sale: true },
  { name: "Windry Mittens", category: "gloves", price: 35.00 },
  { name: "Tuvila Hat", category: "hats", price: 120.00 },
  { name: "Klinto Hat", category: "hats", subcategory: "hats-beanies", price: 65.00 }
]);

db.products.find({});
  1. The commands should result in a list of documents in the local MongoDB collection. Here's a truncated example of the output.

    [
      {
        "_id": { "$oid": "640a146e89286b79b6628eef" },
        "name": "Confira Watch",
        "category": "watches",
        "price": 105
      },
      {
        "_id": { "$oid": "640a146e89286b79b6628ef0" },
        "name": "Diannis Watch",
        "category": "watches",
        "price": 98,
        "sale": true
      },
      ...
    ]
    

    Note

    The object ids (_id) are randomnly generated and will differ from this truncated example output.

  2. Exit the MongoDB shell.

    exit
    
  3. In the client/ directory, create a new .env file.

  4. In the client/.env file, add an environment variable for this value:

    Environment Variable Value
    CONNECTION_STRING The connection string to the Azure Cosmos DB for MongoDB (vCore) cluster. Use the same connection string you used with the mongo shell.
    CONNECTION_STRING=<your-connection-string>
    
  5. Validate that the application is using the database service by changing the context of the terminal to the server/ folder, installing dependencies from Node Package Manager (npm), and then starting the application.

    cd server
    
    npm install
    
    npm start
    
  6. The API automatically opens a browser window to verify that it returns an array of product documents.

  7. Close the extra browser tab/window. Then, close the terminal.

Deploy the MERN application to Azure App Service

Deploy the service and client to Azure App Service to prove that the application works end-to-end. Use secrets in the web apps to store environment variables with credentials and API endpoints.

  1. Within your integrated development environment (IDE), open a new terminal.

  2. Create a shell variable for the name of the pre-existing resource group named resourceGroupName.

    # Variable for resource group name
    resourceGroupName="<existing-resource-group>"
    
  3. Create shell variables for the two web app named serverAppName and clientAppName.

    # Variable for randomnly generated suffix
    let suffix=$RANDOM*$RANDOM
    
    # Variable for web app names with a randomnly generated suffix
    serverAppName="server-app-$suffix"
    clientAppName="client-app-$suffix"
    
  4. If you haven't already, sign in to the Azure CLI using the az login --use-device-code command.

  5. Change the current working directory to the server/ path.

    cd server
    
  6. Create a new web app for the server component of the MERN application with az webapp up.

    az webapp up \
        --resource-group $resourceGroupName \
        --name $serverAppName \
        --sku F1 \
        --runtime "NODE|18-lts"
    
  7. Create a new connection string setting for the server web app named CONNECTION_STRING with az webapp config connection-string set. Use the same value for the connection string you used with the MongoDB shell and .env file earlier in this tutorial.

    az webapp config connection-string set \
        --resource-group $resourceGroupName \
        --name $serverAppName \
        --connection-string-type custom \
        --settings "CONNECTION_STRING=<mongodb-connection-string>"
    
  8. Get the URI for the server web app with az webapp show and store it in a shell variable name d serverUri.

    serverUri=$(az webapp show \
        --resource-group $resourceGroupName \
        --name $serverAppName \
        --query hostNames[0] \
        --output tsv)
    
  9. Use the open-cli package and command from NuGet with npx to open a browser window using the URI for the server web app. Validate that the server app is returning your JSON array data from the MongoDB (vCore) cluster.

    npx open-cli "https://$serverUri/products" --yes
    

    Tip

    Sometimes deployments can finish asynchronously. If you are not seeing what you expect, wait another minute and refresh your browser window.

  10. Change the working directory to the client/ path.

    cd ../client
    
  11. Create a new web app for the client component of the MERN application with az webapp up.

    az webapp up \
        --resource-group $resourceGroupName \
        --name $clientAppName \
        --sku F1 \
        --runtime "NODE|18-lts"
    
  12. Create a new app setting for the client web app named REACT_APP_API_ENDPOINT with az webapp config appsettings set. Use the server API endpoint stored in the serverUri shell variable.

    az webapp config appsettings set \
        --resource-group $resourceGroupName \
        --name $clientAppName \
        --settings "REACT_APP_API_ENDPOINT=https://$serverUri"
    
  13. Get the URI for the client web app with az webapp show and store it in a shell variable name d clientUri.

    clientUri=$(az webapp show \
        --resource-group $resourceGroupName \
        --name $clientAppName \
        --query hostNames[0] \
        --output tsv)
    
  14. Use the open-cli package and command from NuGet with npx to open a browser window using the URI for the client web app. Validate that the client app is rendering data from the server app's API.

    npx open-cli "https://$clientUri" --yes
    

    Tip

    Sometimes deployments can finish asynchronously. If you are not seeing what you expect, wait another minute and refresh your browser window.

  15. Close the terminal.

Clean up resources

When you're working in your own subscription, at the end of a project, it's a good idea to remove the resources that you no longer need. Resources left running can cost you money. You can delete resources individually or delete the resource group to delete the entire set of resources.

  1. To delete the entire resource group, use az group delete.

    az group delete \
        --name $resourceGroupName \
        --yes
    
  2. Validate that the resource group is deleted using az group list.

    az group list
    

Clean up dev environment

You may also wish to clean up your development environment or return it to its typical state.

Deleting the GitHub Codespaces environment ensures that you can maximize the amount of free per-core hours entitlement you get for your account.

  1. Sign into the GitHub Codespaces dashboard (https://github.com/codespaces).

  2. Locate your currently running codespaces sourced from the azure-samples/msdocs-azure-cosmos-db-mongodb-mern-web-app GitHub repository.

    Screenshot of all the running codespaces including their status and templates.

  3. Open the context menu for the codespace and then select Delete.

    Screenshot of the context menu for a single codespace with the delete option highlighted.

Next step

Now that you have built your first application for the MongoDB (vCore) cluster, learn how to migrate your data to Azure Cosmos DB.