HomeLearnQuickstartMongoDB Realm Web SDK Tutorial

MongoDB Realm Web SDK Tutorial

Published: Aug 03, 2021

  • MongoDB
  • Atlas
  • Realm
  • ...

By Maxime Beugnet

Rate this article

#Introduction

In this tutorial blog post, you will learn how to retrieve data from a MongoDB Atlas cluster using the MongoDB Realm Web SDK and display it in a very basic website hosted in MongoDB Realm Static Hosting.

But wait... If we query our MongoDB cluster directly from the front-end code, isn't that super unsafe?

Usually, applications are designed using the 3-tier architecture with a back end that can act as a gatekeeper for the database. This ensures that the queries are authenticated correctly and that appropriate business rules are applied. Also, it avoids sharing your database connection string (with the username and password...) publicly in the front-end code, which is kind of a good idea if you don't want to share your entire database publicly.

No worries! MongoDB Realm is here to save the day! The web SDK actually uses a Realm Application as a serverless back end to solve all the problems I just mentioned.

So in this tutorial, we will build a minimalistic website that will be able to retrieve movie titles from your MongoDB Atlas database and display them in the browser. For this, we will:

  • Create a basic Realm Application to handle the anonymous authentication and set the access rules for our movies collection.
  • Create the website with just one HTML file and one JavaScript file.

#Getting Set Up

For this tutorial, you will need:

  • Load the sample data set as we will need some sample documents from the sample_mflix.movies collection.
Import the sample data set menu in MongoDB Atlas

We will also use jQuery (to keep things as simple as possible) and the Realm Web SDK but it's just a couple of imports in the JavaScript code. You don't need anything else.

#Create a Realm Application

Access Realm by clicking the link at the top in your MongoDB Atlas UI, above your cluster.

Access Realm in the MongoDB Atlas UI

Create a Realm application. If possible, keep it close (same region) to your Atlas Cluster.

Create the Realm Application

Our Realm Web SDK needs to authenticate users to work properly. In this tutorial, we will use the anonymous authentication to keep it simple.

Activating the anonymous authentication in the Realm application

We need to tell our Realm application what our authenticated users can do with each collection. In this case, we want them to access the sample_mflix.movies collection for reads only.

Allow read-only access in the collection rules to the sample_mflix.movies collection

Don't forget to click on Configure Collection to validate this choice. You also need to deploy these modifications.

Click review draft & deploy to deploy the modifications we did to our realm application

#Create a Mini Website with the Realm Web SDK

Now that our Realm application is ready, we can create a mini website to retrieve 20 movie titles from our sample_mflix.movies collection in MongoDB Atlas and display them in our website.

Create a new folder and a new file index.html.

1<!DOCTYPE html>
2<html lang="en">
3<head>
4 <link rel="shortcut icon" type="image/png" href="https://www.mongodb.com/assets/images/global/favicon.ico"/>
5 <script src="https://unpkg.com/realm-web@1.2.0/dist/bundle.iife.js"></script>
6 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
7 <title>My Movie Titles</title>
8</head>
9<body>
10<h1>My Movies</h1>
11<div>
12 <!-- Login anonymously -->
13 <input type="submit" value="LOGIN" onClick="login()">
14 <!-- Finds first 20 movies in movies collection -->
15 <input type="submit" value="FIND 20 MOVIES" onClick="find_movies()">
16</div>
17<!-- Using this div to display the user ID -->
18<div id="user"></div>
19<!-- Using this div to show the 20 movie titles -->
20<div id="movies"></div>
21<!-- Inside this file are the functions used above: login() and find_movies() -->
22<script src="data.js"></script>
23</body>
24</html>

In the same folder, create a file data.js.

1const APP_ID = '<YOUR-REALM-APPID>';
2const ATLAS_SERVICE = 'mongodb-atlas';
3const app = new Realm.App({id: APP_ID});
4
5// Function executed by the LOGIN button.
6const login = async () => {
7 const credentials = Realm.Credentials.anonymous();
8 try {
9 const user = await app.logIn(credentials);
10 $('#user').empty().append("User ID: " + user.id); // update the user div with the user ID
11 } catch (err) {
12 console.error("Failed to log in", err);
13 }
14};
15
16// Function executed by the "FIND 20 MOVIES" button.
17const find_movies = async () => {
18 let collMovies;
19 try {
20 // Access the movies collection through MDB Realm & the readonly rule.
21 const mongodb = app.currentUser.mongoClient(ATLAS_SERVICE);
22 collMovies = mongodb.db("sample_mflix").collection("movies");
23 } catch (err) {
24 $("#user").append("Need to login first.");
25 console.error("Need to log in first", err);
26 return;
27 }
28
29 // Retrieve 20 movie titles (only the titles thanks to the projection).
30 const movies_titles = await collMovies.find({}, {
31 "projection": {
32 "_id": 0,
33 "title": 1
34 },
35 "limit": 20
36 });
37
38 // Access the movies div and clear it.
39 let movies_div = $("#movies");
40 movies_div.empty();
41
42 // Loop through the 20 movie title and display them in the movies div.
43 for (const movie of movies_titles) {
44 let p = document.createElement("p");
45 p.append(movie.title);
46 movies_div.append(p);
47 }
48};

The first line of data.js needs your Realm APPID. You can find it here:

Retrieve the Realm AppID in the Realm UI

In my case, my first line looks like this, but please use your own APPID:

1const APP_ID = 'realmwebsdk-uuldw';

#Deploy the Website in MongoDB Realm Static Hosting

MongoDB Realm - Hosting website feature in the UI

Upload your two files index.html and data.js using the UPLOAD FILES button. Realm will tell you that you are overwriting ./index.html. This is the expected result.

Result of the upload of the 2 files in the MongoDB Realm UI

Don't forget to review and deploy your modification!

Click review draft & deploy to deploy the modifications we did to our realm application

At this point, you should be able to access your website with the provided link, but the DNS can take up to 15 minutes to propagate.

Link to the hosted website and DNS warning message

Try to open the provided link and if that doesn't work yet, feel free to open your local index.html file in your preferred web browser. You should see something like this:

The website with 2 buttons "login" and "find 20 movies".

Click on LOGIN. You are now authenticated with an anonymous user.

The website now displays the user ID.

You can find this user in your Realm application in the App Users menu in MongoDB Realm. Of course, you could use a better authentication provider to secure your application correctly.

The same user ID in the Realm UI.

If you click on the FIND 20 MOVIES button, you should now see a bunch of movie titles that come from your MongoDB Atlas sample collection.

The website now displays 20 movies titles

#Wrapping Up

In this tutorial, you learned how to set up your first website using MongoDB Realm Web SDK. We used jQuery for this simple example, but any recent and popular JavaScript front-end technology like React, Angular, or Vue.js would also work.

MongoDB Realm provides a number of SDKs that can also be useful for your project:

If you have any question, please reach out on the MongoDB Community Forum in the Realm SDKs category.

Rate this article
MongoDB Icon
  • Developer Hub
  • Documentation
  • University
  • Community Forums

© MongoDB, Inc.