MongoDB Stitch Browser SDK
The official MongoDB Stitch Browser SDK for JavaScript/TypeScript.
Index
Documentation
Discussion
Installation
NPM
Run the following in the root directory of your NPM project.
npm install mongodb-stitch-browser-sdk
This will start you off with the core SDK functionality as well as the remote MongoDB service.
See Customized Dependencies (Advanced) below for customizing dependencies.
HTML Script Tags
You can also include the SDK directly in your HTML code using script tags. For core SDK functionality and the remote MongoDB service, use the following:
<script src="https://s3.amazonaws.com/stitch-sdks/js/bundles/4.8.0/stitch.js"></script>
See Customized Dependencies (Advanced) below for customizing dependencies.
Getting Started
Creating a new app with the SDK (NPM)
Set up an application on Stitch
First, you need to create the server-side Stitch app, and (for the purpose of this quick start) enable anonymous authentication:
- Go to https://stitch.mongodb.com/ and log in to MongoDB Atlas.
- Create a new app in your project with your desired name.
- Go to your app in Stitch via Atlas by clicking Stitch Apps in the left side pane and clicking your app.
- Copy your app's client app id by going to Clients on the left side pane and clicking copy on the App ID section.
- Go to Providers from Users in the left side pane and edit and enable "Allow users to log in anonymously".
For detailed instructions, see Create a Stitch App.
Set up an NPM project
Next, you create the source for your client app.
- Ensure that you have
npm
installed. See npmjs.com. - Initialize a new NPM project:
mkdir StitchProject && cd StitchProject
npm init
- Add the MongoDB Stitch Browser SDK:
npm install mongodb-stitch-browser-sdk
- Install webpack.js:
npm install --save-dev webpack webpack-cli
- Add the following field to the
"scripts"
field of the package.json
file that was generated by npm init
:
"scripts": {
"pack": "webpack"
}
- Create directories for your source files and your distributed files:
mkdir src dist
- Create the file
src/index.js
and add the following code, replacing <your-client-app-id>
with the id you retrieved when setting up the application in MongoDB Stitch:
import { Stitch, AnonymousCredential } from 'mongodb-stitch-browser-sdk'
function initializeAndLogin() {
const client = Stitch.initializeDefaultAppClient('<your-client-app-id>');
client.auth.loginWithCredential(new AnonymousCredential()).then(user => {
document.getElementById('auth-status').innerHTML =
`Logged in as anonymous user with id ${user.id}`;
});
}
window.onload = initializeAndLogin;
- Create the file
dist/index.html
and add the following code:
<!doctype html>
<html>
<head>
<title>MongoDB Stitch Sample</title>
</head>
<body>
<script src="main.js"></script>
<div id="auth-status">Logged Out</div>
</body>
</html>
Build and run the app
Finally, you can build and run the app:
- Run the webpack bundler:
npm run pack
- Open
dist/index.html
in your web browser. If everything was configured correctly, you should see a message in the browser window that you are logged in as an anonymous user.
See the Getting Started guide on webpack
's website for more information on how to use webpack to bundle your JavaScript or TypeScript code that uses the Stitch SDK.
Additionally, the JavaScript code above utilizes ES6 features. If you'd like your code to run in older browsers, you'll need to use a transpiler like Babel as part of your bundling process. See babel-loader.
Using the SDK
Initialize the SDK
When your app or webpage is initialized, use Stitch.initializeDefaultAppClient to initialize the Stitch SDK. Replace <your-client-app-id>
with your Stitch application's client app ID:
import { Stitch, AnonymousCredential } from 'mongodb-stitch-browser-sdk'
Stitch.initializeDefaultAppClient('<your-client-app-id>');
Your client app ID can be found in the Stitch UI.
Logging In
- We enabled anonymous authentication in the steps above, so let's log in with it! Add the following anywhere in your code:
const client = Stitch.defaultAppClient;
console.log("logging in anonymously");
client.auth.loginWithCredential(new AnonymousCredential()).then(user => {
console.log(`logged in anonymously as user ${user.id}`)
});
When running this code, you should see the following in your browser's debug console:
logging in anonymously
logged in anonymously as user 58c5d6ebb9ede022a3d75050
See StitchAuth for more information.
Executing a Stitch Function
One of Stitch's powerful features is serverless Functions. Once logged in, the Stitch client can execute remote Stitch Functions using the StitchAppClient.callFunction method:
client.callFunction("echoArg", ["Hello world!"]).then(echoedResult => {
console.log(`Echoed result: ${echoedResult}`);
})
Assuming you've configured your Stitch application to have a function named "echoArg" that returns its argument, you should see a message like:
Echoed result: Hello world!
The echoArg
Function in Stitch would look something like:
exports = function(arg) {
return {arg: arg};
};
Using BSON and Extended JSON
As a convenience, the SDK includes the bson library. You can import it as you would import other classes and values from the SDK.
Here is an example of importing BSON to generate a BSON ObjectID
using ES6:
import { BSON } from 'mongodb-stitch-browser-sdk';
let myObjectId = new BSON.ObjectId();
console.log(`Generated ObjectId: ${myObjectId}`);
And here is an example of importing BSON to generate an ObjectId
using an HTML <script>
tag import:
<!doctype html>
<html>
<head>
<title>MongoDB Stitch BSON Sample</title>
</head>
<body>
<script src="https://s3.amazonaws.com/stitch-sdks/js/bundles/4.8.0/stitch.js"></script>
<script>
function generateObjectId() {
const newObjectId = new stitch.BSON.ObjectId()
document.getElementById('obj-id-display').innerHTML =
`Generated ObjectId: ${newObjectId}`;
}
window.onload = generateObjectId;
</script>
<div id="obj-id-display">Generated ObjectId: None</div>
</body>
</html>
Advanced Topics
Customized Dependencies
For customized dependencies in NPM use the following:
npm install mongodb-stitch-browser-core
npm install mongodb-stitch-browser-services-aws
npm install mongodb-stitch-browser-services-http
npm install mongodb-stitch-browser-services-mongodb-remote
npm install mongodb-stitch-browser-services-twilio
For customized dependencies with HTML script tags use the following:
<script src="https://s3.amazonaws.com/stitch-sdks/js/bundles/4.8.0/stitch-core.js"></script>
<script src="https://s3.amazonaws.com/stitch-sdks/js/bundles/4.8.0/stitch-services-aws.js"></script>
<script src="https://s3.amazonaws.com/stitch-sdks/js/bundles/4.8.0/stitch-services-http.js"></script>
<script src="https://s3.amazonaws.com/stitch-sdks/js/bundles/4.8.0/stitch-services-mongodb-remote.js"></script>
<script src="https://s3.amazonaws.com/stitch-sdks/js/bundles/4.8.0/stitch-services-twilio.js"></script>
Getting a StitchAppClient without Stitch.getDefaultAppClient (Advanced)
In the case that you don't want a single default initialized StitchAppClient
, you can use the following with as many client app IDs as you'd like to initialize clients for multiple app IDs:
const client = Stitch.initializeAppClient("<your-client-app-id>");
You can use the client returned there or anywhere else in your app by using the following:
const client = Stitch.getAppClient("<your-client-app-id>");