Blog App: Create a Web Client¶
Author: Stitch Documentation Team
In this guide, we’ll create the frontend of our blog. Our blog frontend needs to:
- allow users to log in
- allow users to create comments on a blog post
- allow users to view the comments of other users on blog posts
Since our backend is already set up, all we need to do is call the right APIs for each of these actions.
Time required: 15 minutes
What You’ll Need¶
If you have not yet built the backend for the blog, follow the steps in the Create the Backend guide.
Procedure¶
Note
You can download the completed blog.html
file for this
tutorial in the blog
folder in the
tutorials repo.
Create an HTML page¶
Begin by creating a file named blog.html
and copy the following
HTML into the file:
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
:
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:
Paste the following
<script>
tag inblog.html
beneath the tag that imports the Stitch SDK: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.
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:
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.
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
:
Add the following function to the
<script>
tag:Update the
<body>
tag inblog.html
to display comments when the page loads.
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:
Add the
addComment()
function to the<script>
tag:Add a comment form by pasting the following code at the bottom of the
<body>
tag inblog.html
:
Summary¶
Congratulations, you now have a working blog! Try refreshing the page and submitting a comment on the blog post.
What’s Next¶
Check out some of our suggestions to improve your blog even more!