Navigation

Blog App: Create a Web Client

Deployment Type:

Author: Stitch Documentation Team

When completed, you will have a basic Blog app that runs in the browser.

Time required: 15 minutes

What You’ll Need

If you have not yet built the Blog backend app, follow the steps in this guide.

Procedure

Note

You can download the completed blog.html file for this tutorial in the blog folder in the tutorials repo.

1

Create an HTML page

Begin by creating a file named blog.html and copy the following HTML into the file:

blog.html
<html>
  <head>
  </head>
  <body>
    <h3>This is a great blog post</h3>
    <div id="content">
      I like to write about technology because I want to get on the
      front page of hacker news.
    </div>
    <hr>
    <div id="comments"></div>
  </body>
</html>
2

Include the MongoDB Stitch JavaScript SDK

We need the JavaScript SDK to communicate with Stitch from our blog code. To include the SDK, add the following <script> tag to the <head> section of blog.html:

<script src="https://s3.amazonaws.com/stitch-sdks/js/bundles/4/stitch.js"></script>
3

Initialize Stitch Clients

Apps communicate with Stitch by calling methods on client objects from the Stitch SDK. We need to initialize an app client and a MongoDB Service client to store comments in MongoDB.

To set up Stitch:

  1. Paste the following <script> tag in blog.html beneath the tag that imports the Stitch SDK:

    <script>
      // Initialize the App Client
      const client = stitch.Stitch.initializeDefaultAppClient("<your-app-id>");
      // Get a MongoDB Service Client
      const mongodb = client.getServiceClient(
        stitch.RemoteMongoClient.factory,
        "mongodb-atlas"
      );
      // Get a reference to the blog database
      const db = mongodb.db("blog");
    </script>
    
  2. In the code you just pasted, replace <your-app-id> with your Stitch application’s App ID. You can find the App ID on the Clients page of the Stitch UI.

4

Query and Display Comments on Page Load

We can use the MongoDB Service client we just created to query the blog.comments collection. Once we have the comments documents, we can map them to HTML and display them on the blog post.

To query and display comments, add the following function to the <script> tag:

function displayComments() {
  db.collection("comments")
    .find({}, {limit: 1000})
    .toArray()
    .then(docs => {
      const html = docs.map(doc => `<div>${doc.comment}</div>`);
      document.getElementById("comments").innerHTML = html;
    });
}

Important

MongoDB Stitch requires users to log in before interacting with any Stitch service. Even though we configured the rules for the blog.comments collection, this query won’t work unless a user is logged in.

5

Log In and Display Comments On Load

Users log in to Stitch applications with a provider-specific credential object that we pass to the loginWithCredential() function. We created an anonymous authentication provider in Stitch, so we need users to log in with an anonymous credential.

To set up anonymous authentication in blog.html:

  1. Add the following function to the <script> tag:

    function displayCommentsOnLoad() {
      client.auth
        .loginWithCredential(new stitch.AnonymousCredential())
        .then(displayComments)
        .catch(console.error);
    }
    
  2. Update the <body> tag in blog.html to display comments when the page loads.

    <body onload="displayCommentsOnLoad()">
    
6

Add a Form for Submitting Comments

We now have everything we need to query and display comments that are already in MongoDB. All that’s left to do is to wire up a form that lets users insert new comments.

To let users add new comments:

  1. Add the addComment() function to the <script> tag:

    function addComment() {
      const newComment = document.getElementById("new_comment");
      console.log("add comment", client.auth.user.id)
      db.collection("comments")
        .insertOne({ owner_id : client.auth.user.id, comment: newComment.value })
        .then(displayComments);
      newComment.value = "";
    }
    
  2. Add a comment form by pasting the following code at the bottom of the <body> tag in blog.html:

    <hr>
    Add comment:
    <input id="new_comment"><input type="submit" onClick="addComment()">
    

Summary

Congratulations! You now have a working blog app! At this point, you should be able to refresh the page and submit a comment on the blog post.