MongoDB Stitch — Your Application Backend Delivered as a Service
As a developer, agile development is crucial to your workflow. You need to move fast, but boilerplate code for tasks like authentication, integration of third party services, and access to data, often gets in the way of building the core components of your application. When you build client-side applications such as mobile apps or web apps, you typically have to build and deploy your own backend that hosts the services your application will need to call.
MongoDB Stitch simplifies these development and deployment processes by removing the need from building and deploying your own backend.
MongoDB Stitch is a Backend as a Service (BaaS) that allows you to easily configure authentication, data access rules, and services.
In addition, it provides an elastically scalable infrastructure for handling requests and coordinating service and database interactions — meaning that you don’t need to spend time and energy on tasks such as configuring your servers. Using Stitch to handle your backend infrastructure allows you to focus on building out the more complex nuances of your application.
Because security is top of mind at MongoDB, Stitch stores encrypted values for all of your services’ credentials, freeing you, the developer, of the need for a separate secret management system. Once services are enabled, they can be invoked directly using the provided Stitch SDKs or can be used to create stages in Stitch pipelines, which can be defined declaratively using standard JSON.
As an example, you can use Stitch to create a pipeline that would allow you to (1) accept a payment using Stripe via the HTTP service, (2) update the date of purchase and user purchase history in your database, and then (3) send a confirmation email with the Mailgun service. This logic is configured through the Stitch UI and executed on the Stitch infrastructure.
To show you what Stitch is capable of, the team at MongoDB built a sample application for locating and reviewing restaurants, dubbed Platespace.
Create a New MongoDB Stitch App
Start by creating an account or signing into your existing account on MongoDB Atlas. If this is your first time using MongoDB Atlas, please also create a free cluster. Once your cluster is provisioned, head over to Stitch Apps in the left hand navigation.
A new page opens where you can create a new application called Platespace (note: link your new Stitch app to your new MongoDB Atlas cluster). MongoDB Atlas will then take you to the Stitch home page where you can test your connection by:
- Configuring anonymous authentication
- Defining rules on your database’s collections
- Executing a test request
- And, verifying that your application is communicating with Stitch
As a primer for building a Stitch application, let’s go over a few concepts:
You can easily orchestrate data across multiple services by configuring multi-stage pipelines, where each stage acts on the data before passing its results on to the next. Pipelines are reusable functions, stored within the Stitch platform, that you can call from your application frontend, from rules and other pipelines.
You can view, edit, and configure all of your pipelines in the Pipelines tab. Pipelines can help you package and abstract the logic within your application, making it simpler for you to update and manage your codebase without having to push new application code.
You can also make multi-stage pipelines by clicking Add stage in the Stitch UI. In the screenshot above, you see a service pipeline for saving items to a specific collection in the database, and a second stage pipeline for running an S3 image through the Clarifai service.
You’ll see the following pipelines in the Platespace app:
- geoNear: This pipeline is called when a user accesses the restaurants list page. This function gathers restaurants in a user’s location by running a $near query on a collection of restaurants.
- userHasSingleReview: This checks if a user has already written a review for a specific restaurant.
- aggregateRestaurant: This pipeline is called by the updateRatings pipeline, and calculates the average rating and the number of reviews for the current restaurant.
- updateRatings: When the user submits or updates a review, this pipeline updates the averageRating and numberOfRates attributes of the current restaurant document, with the values computed by the aggregateRestaurant pipeline.
Pipelines allow us to reuse logic across multiple services, rules, and other pipelines within Stitch, as well as being able to call them from applications.
Stitch provides a consistent interface to MongoDB’s Database as a Service, MongoDB Atlas, and other 3rd party services. Rather than manually coding against the APIs for each of these services, with Stitch, you can access these external services through a single, native interface from your application’s frontend.
For instance, here’s how you would set up a service such as the Amazon Web Services S3 service:
- Click the “ADD SERVICE” button in the Stitch left-side navigation,
- Select “S3” and enter a name for your service.
- After deploying your service, enter the configuration information. For AWS S3, this includes the AWS Region where your S3 bucket resides, the AWS Access Key ID, and the AWS Secret Access Key.
To complete the configuration of your AWS S3 service, please refer to the instructions available in the README file.
When coding the logic to upload image files to AWS S3, the frontend application can simply invoke a function in the native MongoDB Stitch SDK:
In addition to using one of our pre-configured services, you can also integrate with remote APIs, microservices or other public cloud services with Stitch’s configurable HTTP service. The HTTP service also allows you to safely store confidential information, like API credentials, without making it accessible to your users. In this application, we added Clarifai, an image recognition service that will help us identify objects or elements in images that are submitted with user reviews.
You can define rules to control when a service can be called. For example, we ensure that the Clarifai Service only runs if you use the POST action and specify a URL parameter that is hosted in the api.clarifai.com domain:
When you are setting up your own HTTP service in Stitch, there are no default configuration settings because Stitch doesn’t know the endpoints that service’s API supports or what parameters it expects. This means that service usage is secure by default. You can have sensitive information be predefined within your configured pipeline or your application’s frontend can include it whenever it invokes the service.
In the case of our application, we’re calling the Clarifai service from the processImage pipeline, we register confidential parameters (such as the Clarifai model id and the Bearer token used with that model) with the pipeline so that the frontend application doesn’t expose them to the end user.
We can then call the pipeline from our frontend code, as follows:
Note: The image above shows that the “imagePublicUrl” parameter must be provided when calling the “processImage” pipeline.
In the pipeline above, we pass a dynamic parameter called “imagePublicUrl” containing the URL of the image we just stored in AWS S3. In Stitch, this parameter is then written to the internal URL variable in the “processImage” pipeline via the LET section above. That URL parameter is, in turn, passed to the Clarifai API by referencing it in the ARGS section.
Stitch lets you ensure that all aspects of your application can be tightly controlled with intuitive rules. Specifically, rules allow you to decide whether a specific user has the ability to read or write data for a specific document or field.
Additionally, a service action must be run with a set of arguments or can be only run by specified users. A pipeline can be run by a certain user or only in certain scenarios.
All of these rules can be defined with simple, familiar JSON, and have full access to globally defined Stitch variables, pipelines, and information about the requesting user through expansions.
Access Permission Rules
Stitch allows you to establish user access rules to control the fields, documents, collections, and aggregations that your users can read from and/or write to. These rules can be set up with just a few clicks and simple JSON, rather than you having to write and implement extensive code to enforce user permissions. Should user permissions need to change, you can make those changes through the Stitch UI. Best of all, the changes take effect immediately, without mandating any application updates.
The default write rule we enforce on every collection ensures that if you store an owner_id field that contains the user’s id, then updates to that document can only be performed by the user who created it.
This is accomplished by entering the following code into the Write section of the Rules tab in the mongodb-atlas service:
You can see a full list of rules and configurations in the GitHub README.
Notice that the rule above includes Stitch Expansions (designated with %%). Expansions let you pull in information from outside of a rule or pipeline in order to make them more powerful. In the above rule we call the following expansions:
- %%prevRoot — The original document, prior to any changes
- %%root — The original document as it would be after the database operation
- %%user.id — The user’s id
- %%false — Compares the result of the following call to the “false” value
Operators (such as %and, %or, %not or %exists) are used in Stitch expressions. For instance, the %pipeline operator calls a pipeline within a rule, another pipeline or a Stitch pipeline variable.
Service level rules allow you to specify which service integration actions can be run, and who they can be run by.
Let’s take a look at the rule we created for the UploadToS3 service:
This rule ensures that the only AWS S3 requests that will be made are PUT operations to the “platespace-demo” AWS S3 bucket. Similar to rules for database operations, these rules can also incorporate expansions to become more expressive. When we call the AWS S3 pipeline from our app, the service rule will prevent uploaded images from being sent to any AWS S3 bucket other than “platespace-demo”.
This is especially useful because with AWS S3 it can be tough to limit access to a specific AWS S3 bucket with the API key alone. With Stitch, you can accomplish this with a simple rule, without needing to create additional infrastructure, roles, or permissions.
MongoDB Stitch is currently in beta and the team is excited to begin working with the community to improve the platform. With any luck, this overview provided you with some useful context, and you are now ready to get started building with Stitch. When you are ready to dive in, please sign up for MongoDB Stitch.
Once you’ve got access, jump on over to GitHub to clone the Platespace application and begin building. While you are experimenting with Platespace, or even your own, original application, please send any and all feedback to firstname.lastname@example.org.