Edit

Tutorial: Deploy a Node.js web app with Azure DocumentDB

This tutorial uses the Azure Developer CLI (azd) to deploy an Express.js app to Azure App Service on Linux with Azure DocumentDB, a MongoDB-compatible database service. The app uses Mongoose, a private database endpoint, and an Azure Key Vault reference for its connection string. Azure Developer CLI is the deployment path for this tutorial. Select the Azure Developer CLI instructions to follow the walkthrough.

Azure Cosmos DB for MongoDB (RU) is a separate service and remains an option for RU-based workloads. This tutorial creates a new DocumentDB cluster; it doesn't convert an existing Cosmos DB account or migrate its data.

Important

This deployment creates paid resources, including an M30 DocumentDB cluster with 128 GiB of storage, one shard, and high availability disabled. Review costs and regional availability before deploying. Use a new, uniquely named azd environment and a new resource group. Don't reuse an existing RU-based environment or a resource group containing data or resources you need to keep.

Screenshot of the Express.js task-list interface.

In this tutorial, you learn how to:

  • Provision App Service and Azure DocumentDB with private backend networking.
  • Use the app's managed identity to read a connection secret from Key Vault.
  • Configure Mongoose to use the DocumentDB connection string and application database.
  • Deploy the app, test task operations, and redeploy changes with Azure Developer CLI.
  • Stream diagnostic logs and clean up the new deployment.
  • Use GitHub Codespaces and GitHub Copilot for local development.

Prerequisites

  • An Azure account with an active subscription and permissions to create resources and role assignments. If you don't have an account, you can create one. A free account doesn't make this architecture free.
  • Azure Developer CLI installed. The sample dev container and Azure Cloud Shell include it.
  • A region and subscription that support the template's resources and DocumentDB configuration. Review DocumentDB compute and storage and limitations.
  • Knowledge of Express.js development.
  • A GitHub account for the Codespaces walkthrough.
  • (Optional) A GitHub Copilot account to try the development prompts.

Skip to the end

For a quick deployment, use the complete application template instead of the starter-no-infra walkthrough. In a new directory in your terminal or Azure Cloud Shell, run:

mkdir msdocs-nodejs-mongodb-azure-sample-app
cd msdocs-nodejs-mongodb-azure-sample-app
azd init --template msdocs-nodejs-mongodb-azure-sample-app .
azd auth login
azd up

During initialization, choose a new environment name. During provisioning, select your subscription and a supported location. Supply documentDbAdministratorPassword only at azd's secure parameter prompt. The administrator username defaults to documentdbadmin. Use a strong, unique password that meets the service requirements; the template accepts 8–128 characters. Don't put the password in azd env set, command arguments, .env, or committed parameter files. Protect azd's local secret/configuration storage and don't share the .azure directory.

The complete template already includes the application connection changes. Continue with Verify connection strings, then test the app and clean up. The following walkthrough is an alternative that starts without infrastructure.

About the portal deployment path

This tutorial uses Azure Developer CLI to provision Azure DocumentDB. This walkthrough doesn't cover the Web App + Database portal wizard. Follow the Azure Developer CLI instructions to create the resources, then use the portal to manage them.

For the separate RU-based service, see Azure Cosmos DB for MongoDB (RU). For general application deployment with GitHub Actions, see Deploy to App Service using GitHub Actions. You can still use the portal to manage resources created with azd.

Run the sample

Set up the sample repository on its starter-no-infra branch. Its dev container includes local MongoDB, a cache, and the environment variables for local development. The container database is local MongoDB, not Azure DocumentDB. A GitHub codespace lets you run this environment in a browser.

  1. Sign in to GitHub and fork the sample repository. Unselect Copy the main branch only so that your fork includes the starter branch.
  2. In your fork, select the starter-no-infra branch, then select Code > Create codespace on starter-no-infra. Wait for the codespace to finish setting up.
  3. In the codespace terminal, run npm install && npm start. When port 3000 becomes available, select Open in Browser to view the sample.
  4. Stop the local Express.js app with Ctrl+C before continuing.

Tip

You can ask GitHub Copilot about this repository. For example:

  • @workspace What does this project do?
  • @workspace What does the .devcontainer folder do?

Having issues? Check the Troubleshooting section.

Create Azure resources and deploy a sample app

The infrastructure-only template adds azure.yaml and the infra directory without replacing your application. Its existing template identifier contains cosmos for compatibility. The database resource is Microsoft.DocumentDB/mongoClusters, and it uses the stable 2024-07-01 API.

  1. From the repository root in the codespace terminal, initialize the infrastructure:

    azd init --template nodejs-app-service-cosmos-redis-infra .
    
  2. Confirm initialization in the nonempty directory. Select Keep my existing files unchanged. Enter a new, unique environment name, using lowercase letters, digits, and hyphens. The template creates a resource group named <environment-name>_group. Choose a name that doesn't reuse an existing group.

  3. Before the first azd up, update the application connection code. Open app.js. In getApp, replace the existing mongoUri assignment and the entire mongoose.connect(...).then(...).catch(...) block with:

    const mongoUri = process.env.AZURE_DOCUMENTDB_CONNECTIONSTRING ||
      process.env.AZURE_COSMOS_CONNECTIONSTRING || process.env.MONGODB_URI;
    
    if (!mongoUri || mongoUri.startsWith('@Microsoft.KeyVault(')) {
      throw new Error('Database connection is not configured. Check the database app setting and Key Vault reference status.');
    }
    
    const mongoOptions = process.env.AZURE_DOCUMENTDB_CONNECTIONSTRING
      ? { dbName: process.env.AZURE_DOCUMENTDB_DATABASE || 'todolist' }
      : {};
    
    mongoose.connect(mongoUri, mongoOptions).then(() => {
      console.log('Connected to database');
    }).catch(() => {
      console.error('Error connecting to database. Check configuration, credentials, and private networking.');
    });
    

    This configuration behavior is the same as the complete sample's config/database.js: DocumentDB first, then the legacy AZURE_COSMOS_CONNECTIONSTRING, then local MONGODB_URI. The legacy fallback supports existing application configurations. It doesn't provision an RU account. dbName selects todolist without changing the authentication database or other options in the service-returned URI. The app creates its application database and collections when it first writes data. Don't log the URI or driver error objects that might contain credentials.

    If you use GitHub Copilot, ask: Update the Mongoose connection in app.js to prefer AZURE_DOCUMENTDB_CONNECTIONSTRING, retain AZURE_COSMOS_CONNECTIONSTRING and MONGODB_URI fallbacks, and set dbName from AZURE_DOCUMENTDB_DATABASE (default todolist) only for the DocumentDB setting. Reject missing or unresolved Key Vault references and don't log connection strings or driver error objects. Compare its suggestion with the code preceding this step before deploying. Never paste credentials into chat.

  4. In routes/index.js, replace the console.log(err) call in each of the four database-operation .catch handlers with the corresponding fixed message. Don't log the error object, its message, or the connection string. Keep the existing response handling unchanged.

    Route Replacement error log
    GET / console.error('Database error reading tasks.');
    POST /addTask console.error('Database error adding a task.');
    POST /completeTask console.error('Database error completing a task.');
    POST /deleteTask console.error('Database error deleting a task.');

    The starter branch has its own application files. These replacements are required even when the complete sample's main branch already uses safe error messages. Use synthetic task data during testing because the normal operation logs can include task names or identifiers.

  5. Sign in to Azure:

    azd auth login
    
  6. Provision the new resources and deploy the app:

    azd up
    

    Select your subscription and a supported location. At the secure parameter prompt, supply documentDbAdministratorPassword; it has no default. The username defaults to documentdbadmin. Follow the credential precautions, and don't enter the password as an azd environment variable. Review any partially created resources before retrying a failed deployment or choosing a different region.

The template creates:

  • Resource group: Contains this new deployment's resources.
  • App Service plan and app: A Linux B1 plan running the Node.js app.
  • Virtual network: App Service VNet integration and outbound routing connect the app to private backend endpoints.
  • Azure DocumentDB cluster: MongoDB 8.0, M30 compute, 128 GiB storage, one shard, high availability disabled, and public network access disabled. This configuration uses a provisioned cluster, not an RU or serverless account. It isn't a production high-availability recommendation.
  • Azure Managed Redis: A Balanced B0 instance with private access. Its existing Service Connector manages the Redis connection settings, not the DocumentDB connection.
  • Key vault: Stores the documentdb-connection-string secret and has public network access disabled.
  • Private endpoints and DNS zones: Connect the cluster, vault, and cache to the VNet. DocumentDB uses private endpoint group MongoCluster and zone privatelink.mongocluster.cosmos.azure.com.
  • Log Analytics workspace: Receives the app's diagnostic logs.

The template uses the cluster's service-returned URI and separately URI-encodes the username and password before storing the connection string in Key Vault. It doesn't construct a hostname or output the connection string. The app's system-assigned managed identity has Key Vault Secrets User on the vault. Managed identity reads the secret; the database connection uses native administrator credentials, not passwordless database authentication. For production, separately design an appropriately scoped database application user and credential rotation process.

Verify connection strings

The template configures App Service app settings. Its postprovision hook displays the database setting names, not their secret values:

App Service database app setting names (Redis is managed by Service Connector):
        - AZURE_DOCUMENTDB_CONNECTIONSTRING
        - AZURE_DOCUMENTDB_DATABASE
  1. Open the App Service app in the Azure portal and inspect its environment variable configuration. The POSIX hook also prints a settings-page link (WEB_APP_CONFIG).
  2. Confirm that AZURE_DOCUMENTDB_CONNECTIONSTRING is a Key Vault reference to documentdb-connection-string, and that its reference status is resolved. The reference starts with @Microsoft.KeyVault(...); it isn't the secret itself. Don't retrieve, copy, or print the resolved URI for this check.
  3. Confirm that AZURE_DOCUMENTDB_DATABASE is todolist. Redis settings are managed separately by the Redis Service Connector and aren't included in the two-name output above.

If the reference doesn't resolve, check the app identity's vault role assignment, VNet routing, and private DNS. See Troubleshoot Key Vault references. A successful resource deployment alone doesn't establish database connectivity; test the app next.

Browse to the app

  1. Open the app endpoint displayed after azd deploy (also available as WEB_URI).
  2. Add a task with synthetic test data, refresh the page, and confirm the task persists.
  3. Mark the task complete, then delete it. Refresh again to verify each change persists. These checks exercise create, read, update, and delete operations rather than only testing whether the web page loads.

Screenshot of the Express.js task-list interface with sample tasks.

If these operations fail, use Troubleshooting. The screenshot illustrates the interface, not proof of your database deployment.

Modify sample code and redeploy

After the first deployment works, make an application change in your codespace, such as updating the page text. Keep the connection configuration from Create Azure resources and deploy a sample app. Deploy application changes without reprovisioning the infrastructure:

azd deploy

Open the app and repeat the task checks. GitHub Copilot can help explain the code or suggest a change, but review and test its suggestions before deployment. Review the GitHub Copilot guidance in the frequently asked questions section.

Stream diagnostic logs

App Service captures console messages. The sample's task routes log operations and task counts. Use synthetic data when testing, and review logs for sensitive content before sharing them.

router.get('/', function(req, res, next) {
  Task.find()
    .then((tasks) => {      
      const currentTasks = tasks.filter(task => !task.completed);
      const completedTasks = tasks.filter(task => task.completed === true);

      console.log(`Total tasks: ${tasks.length}   Current tasks: ${currentTasks.length}    Completed tasks:  ${completedTasks.length}`)
      res.render('index', { currentTasks: currentTasks, completedTasks: completedTasks });
    })
    .catch((err) => {
      console.log(err);
      res.send('Sorry! Something went wrong.');
    });
});

The postdeploy hook prints a link by using WEB_APP_LOG_STREAM:

Stream App Service logs at: <URL>

Open the link to inspect App Service logs. Don't dump environment variables or connection strings to diagnose an error. For more logging options, see Enable Azure Monitor OpenTelemetry for .NET, Node.js, Python, and Java applications.

Clean up resources

Back up any data you need. Confirm that the selected azd environment and resource group belong only to this new tutorial deployment, not to an existing RU account or another workload. Then delete the deployment's resources and data:

azd down

Read the prompts before confirming. Verify that the cluster, App Service plan, Redis instance, private endpoints, and other billable resources are removed. Key Vault soft-delete can retain a deleted vault; review any purge prompt carefully and don't purge unrelated vaults. Keep existing RU resources and data until a separate migration, validation, cutover, and rollback plan is complete.

Troubleshooting

The browser page of the deployed app says "Something went wrong."

Check that you updated both the connection URI selection and the dbName option before the first deployment. See Create Azure resources and deploy a sample app. After correcting application code, redeploy it.

Also check that the Key Vault reference resolves and the cluster's private endpoint connection is approved. From the app's network, the service-returned SRV hostname must resolve to private targets and connect with normal TLS certificate validation and valid native database credentials. Don't construct a replacement hostname, disable TLS validation, or enable public access to work around a failure. See DocumentDB Private Link.

Frequently asked questions

How much does this setup cost?

Review current pricing before deployment; this setup is a paid architecture, not a free or serverless database example:

Existing RU-based accounts have separate Azure Cosmos DB pricing. Creating this environment doesn't stop their billing or transfer their data.

How do I connect to the private DocumentDB cluster with other tools?

Use a client on an authorized network path to the cluster's VNet, such as a VM in the VNet or a connected network with a site-to-site VPN. Configure private DNS resolution and retain the service-returned SRV URI and TLS options. See DocumentDB Private Link and Connect with MongoDB Shell.

A local codespace or laptop doesn't automatically have this private network access. Continue using the container's local MongoDB for local development, or arrange an authorized private connection. Don't open public database access just to make a local tool connect.

How do I use GitHub Actions for deployment?

This walkthrough uses azd, not a portal-generated GitHub Actions workflow. To configure continuous deployment separately, see Deploy to App Service using GitHub Actions. Keep database credentials out of workflow files and logs.

What can I do with GitHub Copilot in my codespace?

You might notice that the GitHub Copilot chat view was already there for you when you created the codespace. For your convenience, we include the GitHub Copilot chat extension in the container definition (see .devcontainer/devcontainer.json). However, you need a GitHub Copilot account (30-day free trial available).

A few tips for you when you talk to GitHub Copilot:

  • In a single chat session, the questions and answers build on each other and you can adjust your questions to fine-tune the answer you get.
  • By default, GitHub Copilot doesn't have access to any file in your repository. To ask questions about a file, open the file in the editor first.
  • To let GitHub Copilot have access to all of the files in the repository when preparing its answers, begin your question with @workspace. For more information, see Use the @workspace agent.
  • In the chat session, GitHub Copilot can suggest changes and, with @workspace, even where to make the changes, but it's not allowed to make the changes for you. It's up to you to add the suggested changes and test it.

Here are some other things you can say to fine-tune the answer you get:

  • @workspace Where is MONGODB_URI defined?
  • Which file do I make the change in?
  • Will this change break my app when running locally?