Skip Navigation

Azure Cosmos DB now supports Cross-Origin Resource Sharing (CORS)

Posted on December 4, 2018

Senior Software Engineer, Azure Cosmos DB

Azure Cosmos DB now supports Cross-Origin Resource Sharing (CORS) “allowedOrigins” header for our core SQL API. You can configure this setting via the portal or ARM templates. With CORS support, you can make your web app talk directly to Cosmos DB from the browser using the @azure/cosmos JavaScript library, and get a more responsive, snappy end-user experience by avoiding an extra hop through a middle-tier.

What is Azure Cosmos DB?

Azure Cosmos DB is a globally distributed, multi-model database service that enables you to read and write data from any Azure region. It offers turnkey global distribution, guarantees single-digit millisecond latencies at the 99th percentile, and elastic scaling of throughput and storage.

For the Azure Cosmos DB core SQL API, we offer a JavaScript library which works in both Node.js and browser environments. This library can now take advantage of CORS support. There is no client-side configuration needed to use this feature. Now that the browser can talk directly to Cosmos DB, you can get even higher performance for web scenarios by avoiding the extra hop through a web app. In the sample we link to below, we’re able to directly listen for changes from Cosmos DB, rather than needing to set up an intermediate server using something like websockets.

import {CosmosClient} from "@azure/cosmos";

const client= new CosmosClient({
   endpoint: "https://<your-cosmos-account>documents.azure.com",
   auth: {} /* Permission token or read only key. Avoid master Key */
});

const todos = client.database("TodoApp").container("Todo").items;

todos.readAll().toArray()
     .then(({result})=>{
         for(const item of result) {
             const e = document.createElement("div")
             e.innerText = item.text;
             document.body.prepend(e);
         }
     });

Here is a simple sample of getting TypeScript and Webpack working with the @azure/cosmos library to build an anonymous bulletin app with real-time updates across all the clients, powered entirely by Cosmos DB.

Enabling CORS

To enable CORS, you can use the portal or an ARM template. You can use a wildcard “*” to allow all origins or specify fully qualified domains which are separated by a comma, (i.e., https://www.mydomain.com, https://mydomain.com, https://api.mydomain.com). Today, you cannot use wildcards as part of the domain name (aka https://*.mydomain.net).

To enable CORS in the portal, navigate to your Cosmos DB Account, and select the CORS option from the settings list. From there, you can specify your allowed origins and then select Save to update your account.

Enabling CORS

Using the @azure/cosmos library in a browser

Today, the @azure/cosmos only has the CommonJS version of the library shipped in its package. To use the library in the browser, you’ll need to use a tool like Rollup or Webpack to create a browser compatible library. Certain Node libraries need to have browser mocks provided for them. Below is an example of a webpack config file which has the necessary mock settings.

const path = require("path");

module.exports = {
   entry: "./src/index.ts",
   devtool: "inline-source-map",
   node: {
     net: "mock",
     tls: "mock"
   },
   output: {
     filename: "bundle.js",
     path: path.resolve(__dirname, "dist")
   }
};
 
Another thing to consider in the browser is that you don’t want to use your master key for most situations. It is best to use Resource Tokens or Readonly keys instead. You can refer to this sample on Github to get started understanding how Resource Tokens work and how you can use something like Azure Functions to authenticate and authorize your users before giving them a Resource Token. We will have more blogs soon about how to use these more advanced authentication patterns with your browser based applications.

Get started

To get started, take a look at our @azure/cosmos library on npm and start using it in your browser-based apps. We’d love to hear your feedback! Email askcosmosdb@microsoft.com or log issues in our GitHub repo.

Stay up-to-date on the latest Azure #CosmosDB news and features by following us on Twitter @AzureCosmosDB. We are really excited to see what you will build with Azure Cosmos DB!