Stitch 101:
App Development in a Serverless World
Nick Larew, Sr Developer Educator, MongoDB
Who Am I?
Live in New York City
Work as a Developer Educator for MongoDB
Started developing web apps six years ago
Love Live Music and Cats
Application Architecture
Modern Application Demands
Serve many users across multiple countries and device types
Scale elastically to meet unexpected or inconsistent demand
Coordinate data from multiple sources
Secure data to prevent malicious actors and ensure privacy
Full-Stack Application Components
➔ Authenticate users and allow
them to use app features.
➔ Handle data requests and
execute business logic.
➔ Provide an interface for users to
interact with your app.
➔ Handle user actions and send
requests to the app server.
Client Applications Application Servers Database Servers
➔ Store and search persisted
application data.
➔ Manage data integrity,
consistency, and availability.
Traditional Applications
➔ You develop and host one or
more secure app servers.
➔ You manage database server
connections and authentication.
➔ You research, develop, and
manage all business logic and
application features.
➔ You authenticate and authorize
incoming user requests.
➔ You develop and distribute one
or more frontend applications.
➔ You write custom client code to
connect your frontend to the
application server.
➔ You host static assets, such as
images or audio, on your server.
➔ You maintain all client features
and fix any bugs.
Client Applications Application Servers Database Servers
➔ You configure, provision, and
spin up one or more servers.
➔ You monitor activity logs,
diagnose performance issues,
and handle network failures.
➔ You develop a system to backup
and restore data.
➔ You ensure data integrity and
security.
Traditional Applications
➔ You develop and host one or
more secure app servers.
➔ You manage database server
connections and authentication.
➔ You research, develop, and
manage all business logic and
application features.
➔ You authenticate and authorize
incoming user requests.
➔ You develop and distribute one
or more frontend applications.
➔ You write custom client code to
connect your frontend to the
application server.
➔ You host static assets, such as
images or audio, on your server.
➔ You maintain all client features
and fix any bugs.
Client Applications Application Servers Database Servers
➔ You configure, provision, and
spin up one or more servers.
➔ You monitor activity logs,
diagnose performance issues,
and handle network failures.
➔ You develop a system to backup
and restore data.
➔ You ensure data integrity and
security.
Third-Party Services and APIs
➔ You develop and host one or
more secure app servers.
➔ You manage database server
connections and authentication.
➔ Third-party services handle
complex or common tasks that
are not unique to your app.
➔ Users can log in through another
service using OAuth or JWT.
➔ You develop and distribute one
or more frontend applications.
➔ You write custom client code to
connect your frontend to the
application server.
➔ You host static assets, such as
images or audio, on your server.
➔ You maintain all client features
and fix any bugs.
Client Applications Application Servers Database Servers
➔ You configure, provision, and
spin up one or more servers.
➔ You monitor activity logs,
diagnose performance issues,
and handle network failures.
➔ You develop a system to backup
and restore data.
➔ You ensure data integrity and
security.
Service-Oriented Architectures
➔ You develop and host one or
more secure app servers.
➔ You manage database service
connections and authentication.
➔ Most features are modeled as a
combination of internal and
third-party services.
➔ Users can log in through another
service using OAuth or JWT.
➔ You develop and distribute one
or more frontend applications.
➔ You write custom client code to
connect your frontend to the
application server.
➔ A hosting service manages and
distributes static assets.
➔ You maintain most client
features and fix most bugs.
Client Applications Application Servers Database Servers
➔ A database service hosts and
manages data infrastructure.
➔ The service monitors activity logs
and automatically handles
network failures.
➔ The service can automatically
backup and restore data.
➔ The service enforces data
security best practices.
Serverless Architectures
➔ Application servers are managed
and deployed as a service.
➔ The serverless platform handles
application requests and
database queries as a service.
➔ Features are a combination of
internal and third-party services.
➔ Users can log in through another
service using OAuth or JWT.
➔ You develop and distribute one
or more frontend applications.
➔ Your frontend connects to the
application platform with a native
SDK, driver, or library.
➔ A hosting service manages and
distributes static assets.
➔ Common “boilerplate” features
are handled by the app platform.
Client Applications Application Servers Database Servers
➔ A database service hosts and
manages data infrastructure.
➔ The service monitors activity logs
and automatically handles
network failures.
➔ The service can automatically
backup and restore data.
➔ The service enforces data
security best practices.
Stitch Application Stack
➔ Authenticate users and allow
them to use app features.
➔ Handle data requests and
execute business logic.
➔ Provide an interface for users to
interact with your app.
➔ Handle user actions and send
requests to the app server.
Client Applications Application Servers Database Servers
➔ Store and search persisted
application data.
➔ Manage data integrity,
consistency, and availability.
Demo: Concert Finder
Demo Application Overview
Functionality
➔ Find concerts happening next week in your neighborhood
➔ Add some favorite venues to your personal list
➔ View other users’ favorite venues
Services
➔ Eventful
◆ Search for upcoming events and venues close to an address
➔ Google Maps
◆ Geocode addresses & locations
Demo Application Overview
Follow Along
concerts.nlarew.com
See the Code
github.com/nlarew/stitch-concert-finder
User Authentication
// Import Stitch Client SDK
import {
Stitch,
UserPasswordCredential
} from "mongodb-stitch-browser-sdk";
// Connect a client to your Stitch app
const appId = "myapp-abcde";
const app = Stitch.initializeAppClient(appId);
// Log in using user-provided credentials
const credential = new UserPasswordCredential(
"SomeUser465@example.com",
"myPassword"
)
// Log in using user-provided credentials
app.auth.loginWithCredential(credential)
.then(user => {
console.log(`Logged in as: ${user}`)
})
Built-In Identity Providers
➔ Anonymous
➔ Email / Password
➔ OAuth 2.0 (Facebook & Google)
➔ API Key (Server & User)
➔ Custom (Bring Your Own Auth)
Application Users
➔ Associated with one or more identities
➔ Must authenticate to send requests
➔ Trigger authentication events
MongoDB Service
// Import MongoDB Service
import {
Stitch,
RemoteMongoClient
} from "mongodb-stitch-browser-sdk";
const app = Stitch.getAppClient("myapp-abcde");
// Instantiate a MongoDB service client
const mongo = app.getServiceClient(
RemoteMongoClient.factory,
"myCluster"
)
const myCollection = mongo
.db("myDb")
.collection("myColl");
// Query MongoDB directly from your application
myCollection.find({}).toArray().then(docs => {
console.log("Found documents:", docs)
})
Query Anywhere
➔ Work with standard MQL queries
➔ Dynamically control what each user sees
Schemas & Filters
➔ Configure the shape and contents of
documents in a collection.
➔ Validate changes to a document
Real-time Change Streams
➔ Watch for changes to documents
External Services
exports = async function() {
// Instantiate an AWS S3 service client
const aws = context.services.get("myAWS");
const s3 = aws.s3("us-east-1");
// Send a GetObject request for a cool image
const result = await s3.GetObject({
"Bucket": "myAppImages",
"Key": "cool-image.png",
})
// Convert the image binary to a string
const imageData = result.Body.text()
return imageData
}
Connect with Service Interfaces
➔ Add credentials to built-in service interfaces
➔ Configure custom HTTP services
Send Requests with Service Actions
➔ Call methods in Functions and SDKs
➔ Authorize actions with dynamic rules
Receive Requests with Webhooks
➔ Receive incoming HTTP payloads
➔ Handle events and requests in a Function
Functions & Triggers
exports = function(changeEvent) {
// Parse values from the insert change event
// changeEvent.operationType === "INSERT"
const insertedDoc = changeEvent.fullDocument
const { _id, name } = insertedDoc;
// Instantiate a MongoDB service client
const cluster = context.services.get("myCluster");
const myDb = cluster.db("myDb");
const myColl = myDb.collection("myColl");
myColl.updateOne({ _id }, {
"$set": { "someField": "$set" }
})
}
Invoke Serverless Functions
➔ Written in JavaScript (ES6+)
➔ Execute dynamically based on context
➔ Run as a specific application user
➔ Connect to your application components
➔ Callable from an SDK or another Function
Trigger Functions on Events
➔ React to changes in a MongoDB collection
➔ Execute logic when users are created or log in
➔ Schedule functions with CRON expressions
Server-Side Rules
// Only return documents where the user’s id
// is the value of the "owner_id" field.
{
"owner_id": "%%user.id",
}
// Run a function to determine if the user is
// authorized to insert a new document.
{ "%%true": {
"%function": {
"name": "isAuthorizedUser",
"arguments": ["%%root._id", "%%user.id"]
}
} }
// Validate service action arguments
{
"%%args.url": "https://www.mongodb.com/",
}
Declarative Expressions
➔ Specify rule conditions with a document
➔ Access specific request/document values.
Dynamic Evaluation
➔ Add complex and/or personalized rules with
expansions and operators.
Secure by Default
➔ If an action does not pass any rule, Stitch
prevents the action
What I Did What I Didn’t Do
Allowed users to create accounts
Retrieved and cached data from
external services
Queried Data from MongoDB
Defined rules to manage user
access to data
Deploy application server
infrastructure
Hassle with cryptography and
complex authentication flows
Configure, host, and manage a
database
Next Steps
Stitch Docs
docs.mongodb.com/stitch
Free Online Courses
university.mongodb.com
Get Started
mongodb.com/cloud/stitch
Thank You!

MongoDB.local Berlin: App development in a Serverless World

  • 1.
    Stitch 101: App Developmentin a Serverless World Nick Larew, Sr Developer Educator, MongoDB
  • 2.
    Who Am I? Livein New York City Work as a Developer Educator for MongoDB Started developing web apps six years ago Love Live Music and Cats
  • 3.
  • 4.
    Modern Application Demands Servemany users across multiple countries and device types Scale elastically to meet unexpected or inconsistent demand Coordinate data from multiple sources Secure data to prevent malicious actors and ensure privacy
  • 5.
    Full-Stack Application Components ➔Authenticate users and allow them to use app features. ➔ Handle data requests and execute business logic. ➔ Provide an interface for users to interact with your app. ➔ Handle user actions and send requests to the app server. Client Applications Application Servers Database Servers ➔ Store and search persisted application data. ➔ Manage data integrity, consistency, and availability.
  • 6.
    Traditional Applications ➔ Youdevelop and host one or more secure app servers. ➔ You manage database server connections and authentication. ➔ You research, develop, and manage all business logic and application features. ➔ You authenticate and authorize incoming user requests. ➔ You develop and distribute one or more frontend applications. ➔ You write custom client code to connect your frontend to the application server. ➔ You host static assets, such as images or audio, on your server. ➔ You maintain all client features and fix any bugs. Client Applications Application Servers Database Servers ➔ You configure, provision, and spin up one or more servers. ➔ You monitor activity logs, diagnose performance issues, and handle network failures. ➔ You develop a system to backup and restore data. ➔ You ensure data integrity and security.
  • 7.
    Traditional Applications ➔ Youdevelop and host one or more secure app servers. ➔ You manage database server connections and authentication. ➔ You research, develop, and manage all business logic and application features. ➔ You authenticate and authorize incoming user requests. ➔ You develop and distribute one or more frontend applications. ➔ You write custom client code to connect your frontend to the application server. ➔ You host static assets, such as images or audio, on your server. ➔ You maintain all client features and fix any bugs. Client Applications Application Servers Database Servers ➔ You configure, provision, and spin up one or more servers. ➔ You monitor activity logs, diagnose performance issues, and handle network failures. ➔ You develop a system to backup and restore data. ➔ You ensure data integrity and security.
  • 8.
    Third-Party Services andAPIs ➔ You develop and host one or more secure app servers. ➔ You manage database server connections and authentication. ➔ Third-party services handle complex or common tasks that are not unique to your app. ➔ Users can log in through another service using OAuth or JWT. ➔ You develop and distribute one or more frontend applications. ➔ You write custom client code to connect your frontend to the application server. ➔ You host static assets, such as images or audio, on your server. ➔ You maintain all client features and fix any bugs. Client Applications Application Servers Database Servers ➔ You configure, provision, and spin up one or more servers. ➔ You monitor activity logs, diagnose performance issues, and handle network failures. ➔ You develop a system to backup and restore data. ➔ You ensure data integrity and security.
  • 9.
    Service-Oriented Architectures ➔ Youdevelop and host one or more secure app servers. ➔ You manage database service connections and authentication. ➔ Most features are modeled as a combination of internal and third-party services. ➔ Users can log in through another service using OAuth or JWT. ➔ You develop and distribute one or more frontend applications. ➔ You write custom client code to connect your frontend to the application server. ➔ A hosting service manages and distributes static assets. ➔ You maintain most client features and fix most bugs. Client Applications Application Servers Database Servers ➔ A database service hosts and manages data infrastructure. ➔ The service monitors activity logs and automatically handles network failures. ➔ The service can automatically backup and restore data. ➔ The service enforces data security best practices.
  • 10.
    Serverless Architectures ➔ Applicationservers are managed and deployed as a service. ➔ The serverless platform handles application requests and database queries as a service. ➔ Features are a combination of internal and third-party services. ➔ Users can log in through another service using OAuth or JWT. ➔ You develop and distribute one or more frontend applications. ➔ Your frontend connects to the application platform with a native SDK, driver, or library. ➔ A hosting service manages and distributes static assets. ➔ Common “boilerplate” features are handled by the app platform. Client Applications Application Servers Database Servers ➔ A database service hosts and manages data infrastructure. ➔ The service monitors activity logs and automatically handles network failures. ➔ The service can automatically backup and restore data. ➔ The service enforces data security best practices.
  • 11.
    Stitch Application Stack ➔Authenticate users and allow them to use app features. ➔ Handle data requests and execute business logic. ➔ Provide an interface for users to interact with your app. ➔ Handle user actions and send requests to the app server. Client Applications Application Servers Database Servers ➔ Store and search persisted application data. ➔ Manage data integrity, consistency, and availability.
  • 12.
  • 13.
    Demo Application Overview Functionality ➔Find concerts happening next week in your neighborhood ➔ Add some favorite venues to your personal list ➔ View other users’ favorite venues Services ➔ Eventful ◆ Search for upcoming events and venues close to an address ➔ Google Maps ◆ Geocode addresses & locations
  • 14.
    Demo Application Overview FollowAlong concerts.nlarew.com See the Code github.com/nlarew/stitch-concert-finder
  • 15.
    User Authentication // ImportStitch Client SDK import { Stitch, UserPasswordCredential } from "mongodb-stitch-browser-sdk"; // Connect a client to your Stitch app const appId = "myapp-abcde"; const app = Stitch.initializeAppClient(appId); // Log in using user-provided credentials const credential = new UserPasswordCredential( "SomeUser465@example.com", "myPassword" ) // Log in using user-provided credentials app.auth.loginWithCredential(credential) .then(user => { console.log(`Logged in as: ${user}`) }) Built-In Identity Providers ➔ Anonymous ➔ Email / Password ➔ OAuth 2.0 (Facebook & Google) ➔ API Key (Server & User) ➔ Custom (Bring Your Own Auth) Application Users ➔ Associated with one or more identities ➔ Must authenticate to send requests ➔ Trigger authentication events
  • 16.
    MongoDB Service // ImportMongoDB Service import { Stitch, RemoteMongoClient } from "mongodb-stitch-browser-sdk"; const app = Stitch.getAppClient("myapp-abcde"); // Instantiate a MongoDB service client const mongo = app.getServiceClient( RemoteMongoClient.factory, "myCluster" ) const myCollection = mongo .db("myDb") .collection("myColl"); // Query MongoDB directly from your application myCollection.find({}).toArray().then(docs => { console.log("Found documents:", docs) }) Query Anywhere ➔ Work with standard MQL queries ➔ Dynamically control what each user sees Schemas & Filters ➔ Configure the shape and contents of documents in a collection. ➔ Validate changes to a document Real-time Change Streams ➔ Watch for changes to documents
  • 17.
    External Services exports =async function() { // Instantiate an AWS S3 service client const aws = context.services.get("myAWS"); const s3 = aws.s3("us-east-1"); // Send a GetObject request for a cool image const result = await s3.GetObject({ "Bucket": "myAppImages", "Key": "cool-image.png", }) // Convert the image binary to a string const imageData = result.Body.text() return imageData } Connect with Service Interfaces ➔ Add credentials to built-in service interfaces ➔ Configure custom HTTP services Send Requests with Service Actions ➔ Call methods in Functions and SDKs ➔ Authorize actions with dynamic rules Receive Requests with Webhooks ➔ Receive incoming HTTP payloads ➔ Handle events and requests in a Function
  • 18.
    Functions & Triggers exports= function(changeEvent) { // Parse values from the insert change event // changeEvent.operationType === "INSERT" const insertedDoc = changeEvent.fullDocument const { _id, name } = insertedDoc; // Instantiate a MongoDB service client const cluster = context.services.get("myCluster"); const myDb = cluster.db("myDb"); const myColl = myDb.collection("myColl"); myColl.updateOne({ _id }, { "$set": { "someField": "$set" } }) } Invoke Serverless Functions ➔ Written in JavaScript (ES6+) ➔ Execute dynamically based on context ➔ Run as a specific application user ➔ Connect to your application components ➔ Callable from an SDK or another Function Trigger Functions on Events ➔ React to changes in a MongoDB collection ➔ Execute logic when users are created or log in ➔ Schedule functions with CRON expressions
  • 19.
    Server-Side Rules // Onlyreturn documents where the user’s id // is the value of the "owner_id" field. { "owner_id": "%%user.id", } // Run a function to determine if the user is // authorized to insert a new document. { "%%true": { "%function": { "name": "isAuthorizedUser", "arguments": ["%%root._id", "%%user.id"] } } } // Validate service action arguments { "%%args.url": "https://www.mongodb.com/", } Declarative Expressions ➔ Specify rule conditions with a document ➔ Access specific request/document values. Dynamic Evaluation ➔ Add complex and/or personalized rules with expansions and operators. Secure by Default ➔ If an action does not pass any rule, Stitch prevents the action
  • 20.
    What I DidWhat I Didn’t Do Allowed users to create accounts Retrieved and cached data from external services Queried Data from MongoDB Defined rules to manage user access to data Deploy application server infrastructure Hassle with cryptography and complex authentication flows Configure, host, and manage a database
  • 21.
    Next Steps Stitch Docs docs.mongodb.com/stitch FreeOnline Courses university.mongodb.com Get Started mongodb.com/cloud/stitch
  • 22.