EventGet 50% off your ticket to MongoDB.local NYC on May 2. Use code Web50!Learn more >>
MongoDB Developer
Atlas
plus
Sign in to follow topics
MongoDB Developer Centerchevron-right
Developer Topicschevron-right
Productschevron-right
Atlaschevron-right

Create a REST API with Cloudflare Workers and MongoDB Atlas

Luke Edwards, Maxime Beugnet7 min read • Published Nov 15, 2021 • Updated Mar 29, 2024
ServerlessCloudflareAtlasTypeScript
Facebook Icontwitter iconlinkedin icon
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.
Note: In this tutorial, the worker isn't using any form of caching. While the connection between MongoDB and the Atlas serverless application is established and handled automatically in the Atlas App Services back end, each new query sent to the worker will require the user to go through the authentication and authorization process before executing any query. In this tutorial, we are using API keys to handle this process but Atlas App Services offers many different authentication providers.

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. ;-)

Prerequisites

  • 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:
Cloudflare subdomain creation

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.
MongoDB Atlas App Services
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.
Atlas App Service AppID

Authentication Via API Keys

Head to Authentication > API Keys.
Authentication by API keys
Activate the provider and save the draft.
Activate authentication by API keys
We need to create an API key, but we can only do so if the provider is already deployed. Click on review and deploy.
Review draft and deploy button
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.
API key
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".
Access rules and click to create a new collection
Next, name your database cloudflare and collection todos. Click create!
Create a new collection to add a rule
Each document in this collection will belong to a unique user defined by the owner_id 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. Add the rule readOwnWriteOwn in the Other presets.
Rule Read Own Write Own
After adding this preset role, you can double-check the rule by clicking on the Advanced view. It should contain the following:
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_ATLAS_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.
New worker created in your cloudflare account

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_ATLAS_APP_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.

Facebook Icontwitter iconlinkedin icon
Rate this tutorial
star-empty
star-empty
star-empty
star-empty
star-empty
Related
Article

Build an E-commerce Search Using MongoDB Vector Search and OpenAI


Mar 12, 2024 | 12 min read
Tutorial

Synchronize Your Mobile Application With MongoDB Atlas and Google Cloud MySQL


Feb 08, 2024 | 6 min read
Tutorial

Learn to Build AI-Enhanced Retail Search Solutions with MongoDB and Databricks


Sep 25, 2023 | 14 min read
Tutorial

MongoDB Atlas with Terraform


Jan 23, 2024 | 9 min read
Table of Contents