Atlas
MongoDB Developer Centerchevron-right
Developer Topicschevron-right
Productschevron-right
Atlaschevron-right

Create a REST API with Cloudflare Workers and MongoDB Atlas

Luke Edwards, Maxime BeugnetPublished Nov 15, 2021 • Updated Sep 29, 2022
ServerlessCloudflareAtlasTypeScript
Copy Link
facebook icontwitter iconlinkedin icon
random alt
Rate this tutorial
star-empty
star-empty
star-empty
star-empty
star-empty

Introduction

Cloudflare Workers provides a serverless execution environment that allows you to create entirely new applications or augment existing ones without configuring or maintaining infrastructure.
MongoDB Atlas allows you to create, manage, and monitor MongoDB clusters in the cloud provider of your choice (AWS, GCP, or Azure) while the Web SDK can provide a layer of authentication and define access rules to the collections.
In this blog post, we will combine all these technologies together and create a REST API with a Cloudflare worker using a MongoDB Atlas cluster to store the data.

TL;DR!

The worker is in this GitHub repository. The README will get you up and running in no time, if you know what you are doing. Otherwise, I suggest you follow this step-by-step blog post. ;-)

Prerequisistes

  • NO credit card! You can run this entire tutorial for free!
  • Git and cURL.
  • Cloudflare account (free plan is fine) with a *.workers.dev subdomain for the workers. Follow steps 1 to 3 from this documentation to get everything you need.
We will create the Atlas App Services application (formerly known as a MongoDB Realm application) together in the next section. This will provide you the AppID and API key that we need.
To deploy our Cloudflare worker, we will need:
  • The application ID (top left corner in your app—see next section).
  • The Cloudflare account login/password.
  • The Cloudflare account ID (in Workers tab > Overview).
To test (or interact with) the REST API, we need:
  • The authentication API key (more about that below, but it's in Authentication tab > API Keys).
  • The Cloudflare *.workers.dev subdomain (in Workers tab > Overview).
It was created during this step of your set-up:

Create and Configure the Atlas Application

To begin with, head to your MongoDB Atlas main page where you can see your cluster and access the 'App Services' tab at the top.
Create an empty application (no template) as close as possible to your MongoDB Atlas cluster to avoid latency between your cluster and app. My app is "local" in Ireland (eu-west-1) in my case.
Now that our app is created, we need to set up two things: authentication via API keys and collection rules. Before that, note that you can retrieve your app ID in the top left corner of your new application.
Authentication Via API Keys
Head to Authentication > API Keys.
Activate the provider and save the draft.
We need to create an API key, but we can only do so if the provider is already deployed. Click on review and deploy.
Now you can create an API key and save it somewhere! It will only be displayed once. If you lose it, discard this one and create a new one.
We only have a single user in our application as we only created a single API key. Note that this tutorial would work with any other authentication method if you update the authentication code accordingly in the worker.
Collection Rules
By default, your application cannot access any collection from your MongoDB Atlas cluster. To define how users can interact with the data, you must define roles and permissions.
In our case, we want to create a basic REST API where each user can read and write their own data in a single collection todos in the cloudflare database.
Head to the Rules tab and let's create this new cloudflare.todos collection.
First, click "create a collection".
Next, name your database cloudflare and collection todos. Click create!
Each document in this collection will belong to a unique user defined by the owner field. This field will contain the user ID that you can see in the App Users tab.
To limit users to only reading and writing their own data, click on your new todos collection in the Rules UI. Start with the read and write all default role.
Now, edit the default role's name to owner and add {"owner": "user.id"} in the "Apply When" section.
You can now click one more time on Review Draft and Deploy. Our application is now ready to use.

Set Up and Deploy the Cloudflare Worker

The Cloudflare worker is available in GitHub repository. Let's clone the repository.
Now that we have the worker template, we just need to change the configuration to deploy it on your Cloudflare account.
Edit the file wrangler.toml:
  • Replace CLOUDFLARE_ACCOUNT_ID with your real Cloudflare account ID.
  • Replace MONGODB_REALM_APPID with your real MongoDB Atlas App Services app ID.
You can now deploy your worker to your Cloudflare account using Wrangler:
Head to your Cloudflare account. You should now see your new worker in the Workers tab > Overview.

Check Out the REST API Code

Before we test the API, please take a moment to read the code of the REST API we just deployed, which is in the src/index.ts file:

Test the REST API

Now that you are a bit more familiar with this REST API, let's test it!
Note that we decided to pass the values as parameters and the authorization API key as a header like this:
You can use Postman or anything you want to test your REST API, but to make it easy, I made some bash script in the api_tests folder.
In order to make them work, we need to edit the file api_tests/variables.sh and provide them with:
  • The Cloudflare worker URL: Replace YOUR_SUBDOMAIN, so the final worker URL matches yours.
  • The MongoDB Atlas App Service API key: Replace YOUR_REALM_AUTH_API_KEY with your auth API key.
Finally, we can execute all the scripts like this, for example:
As you can see, the REST API works like a charm!

Wrap Up

Cloudflare offers a Workers KV product that can make for a quick combination with Workers, but it's still a simple key-value datastore and most applications will outgrow it. By contrast, MongoDB is a powerful, full-featured database that unlocks the ability to store, query, and index your data without compromising the security or scalability of your application.
As demonstrated in this blog post, it is possible to take full advantage of both technologies. As a result, we built a powerful and secure serverless REST API that will scale very well.
Another option for connecting to Cloudflare is the MongoDB Atlas Data API. The Atlas Data API provides a lightweight way to connect to MongoDB Atlas that can be thought of as similar to a REST API. To learn more, view this tutorial from my fellow developer advocate Mark Smith!
If you have questions, please head to our developer community website where the MongoDB engineers and the MongoDB community will help you build your next big idea with MongoDB. If your question is related to Cloudflare, I encourage you to join their active Discord community.

Copy Link
facebook icontwitter iconlinkedin icon
Rate this tutorial
star-empty
star-empty
star-empty
star-empty
star-empty
Related
Tutorial
Create a Multi-Cloud Cluster with MongoDB Atlas

Sep 23, 2022
Tutorial
Maintaining a Geolocation Specific Game Leaderboard with Phaser and MongoDB

Sep 23, 2022
Tutorial
Build Your Own Function Retry Mechanism with Realm

Jul 19, 2022
Tutorial
Building an Autocomplete Form Element with Atlas Search and JavaScript

Sep 23, 2022
Table of Contents