# mongodb-stitch-browser-sdk

> MongoDB Stitch JavaScript SDK - Browser SDK

Latest version **4.8.0** (published 2020-01-03) · Apache-2.0 license · 0 weekly downloads

> **Deprecated.** This package is deprecated.

## Install

```sh
npm install mongodb-stitch-browser-sdk
pnpm add mongodb-stitch-browser-sdk
yarn add mongodb-stitch-browser-sdk
bun add mongodb-stitch-browser-sdk
```

## Health

**Score 10/100 (F)** — status: deprecated.

Negative: deprecated.

## Facts

| | |
|---|---|
| Version | 4.8.0 |
| Published | 2020-01-03 |
| First published | 2018-06-20 |
| Weekly downloads | 0 |
| License | Apache-2.0 |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Dependencies | 2 |
| Unpacked size | 1.2 MB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 111 |
| Author | MongoDB Inc. |
| Maintainers | adamchel_mongodb, edaniels, jsflax, mpobrien, unicodesnowman |
| Keywords | mongodb, aws, twilio, http, mobile, serverless, stitch, atlas |

## Links

- npm: https://www.npmjs.com/package/mongodb-stitch-browser-sdk
- Repository: https://github.com/mongodb/stitch-js-sdk
- Homepage: https://github.com/mongodb/stitch-js-sdk#readme
- Issues: https://github.com/mongodb/stitch-js-sdk/issues
- npm.io page: https://npm.io/package/mongodb-stitch-browser-sdk

## Dependencies (2)

- [mongodb-stitch-browser-core](https://npm.io/package/mongodb-stitch-browser-core.md) ^4.8.0
- [mongodb-stitch-browser-services-mongodb-remote](https://npm.io/package/mongodb-stitch-browser-services-mongodb-remote.md) ^4.8.0

## Alternatives

- [angular-pipes](https://npm.io/package/angular-pipes.md) — 5.6K weekly downloads
- [@ng-web-apis/midi](https://npm.io/package/@ng-web-apis/midi.md) — 2.6K weekly downloads
- [happn-3](https://npm.io/package/happn-3.md) — 1.6K weekly downloads
- [@opensip-cli/lang-go](https://npm.io/package/@opensip-cli/lang-go.md) — 1.2K weekly downloads
- [@temporal-architect/claude-plugin](https://npm.io/package/@temporal-architect/claude-plugin.md) — 335 weekly downloads

## Recent versions

- 4.8.0 (latest) — 2020-01-03
- 4.9.0 (next) — 2020-01-31
- 4.0.15-beta-2.0 (beta) — 2018-11-26
- 4.0.14-2 (alpha) — 2018-10-12
- 4.7.1 — 2019-11-11
- 4.7.0 — 2019-11-06
- 4.6.0 — 2019-10-23
- 4.5.0 — 2019-07-12
- 4.4.1 — 2019-06-11
- 4.4.0 — 2019-05-16
- 4.3.2 — 2019-03-12
- 4.3.1 — 2019-03-05
- 4.3.0 — 2019-02-15
- 4.2.0 — 2019-01-29
- 4.1.3 — 2019-01-24
- … 32 more at https://npm.io/package/mongodb-stitch-browser-sdk/versions

## README

[![Join the chat at https://gitter.im/mongodb/stitch](https://badges.gitter.im/mongodb/stitch.svg)](https://gitter.im/mongodb/stitch?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

# MongoDB Stitch Browser SDK 

The official [MongoDB Stitch](https://www.mongodb.com/cloud/stitch) Browser SDK for JavaScript/TypeScript.

## Index
- [Documentation](#documentation)
- [Discussion](#discussion)
- [Installation](#installation)
- [Getting Started](#getting-started)

## Documentation
* [MongoDB Stitch Documentation](https://docs.mongodb.com/stitch/)
* [API Reference Manual](https://docs.mongodb.com/stitch-sdks/js/4/index.html)

## Discussion
* [MongoDB Stitch Users - Google Group](https://groups.google.com/d/forum/mongodb-stitch-users)
* [MongoDB Stitch Announcements - Google Group](https://groups.google.com/d/forum/mongodb-stitch-announce)

## Installation

### NPM

Run the following in the root directory of your NPM project.

```bash
npm install mongodb-stitch-browser-sdk
```

This will start you off with the [core SDK functionality](classes/stitch.html) as well as the [remote MongoDB service](modules/remotemongoclient.html).

See [Customized Dependencies (Advanced)](#customized-dependencies) 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:

```html
<script src="https://s3.amazonaws.com/stitch-sdks/js/bundles/4.8.0/stitch.js"></script>
```

See [Customized Dependencies (Advanced)](#customized-dependencies) 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:

1. Go to [https://stitch.mongodb.com/](https://stitch.mongodb.com/) and log in to MongoDB Atlas.
2. Create a new app in your project with your desired name.
3. Go to your app in Stitch via Atlas by clicking Stitch Apps in the left side pane and clicking your app.
3. Copy your app's client app id by going to Clients on the left side pane and clicking copy on the App ID section.
4. 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](https://docs.mongodb.com/stitch/procedures/create-stitch-app/).

#### Set up an NPM project

Next, you create the source for your client app.

1. Ensure that you have `npm` installed. See [npmjs.com](https://www.npmjs.com).
2. Initialize a new NPM project: 

```bash
mkdir StitchProject && cd StitchProject
npm init
```

3. Add the MongoDB Stitch Browser SDK:

```bash
npm install mongodb-stitch-browser-sdk
```

4. Install [webpack.js](https://webpack.js.org):

```bash
npm install --save-dev webpack webpack-cli
```

5. Add the following field to the `"scripts"` field of the `package.json` file that was generated by `npm init`:

```json
"scripts": {
    "pack": "webpack"
}
```

6. Create directories for your source files and your distributed files:

```bash
mkdir src dist
```

7. 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:

```javascript
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;
```

8. Create the file `dist/index.html` and add the following code:

```html
<!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:

1. Run the webpack bundler:

```bash
npm run pack
```

2. 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](https://webpack.js.org/guides/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](https://babeljs.io/) as part of your bundling process. See [babel-loader](https://github.com/babel/babel-loader).

### Using the SDK

#### Initialize the SDK

When your app or webpage is initialized, use [Stitch.initializeDefaultAppClient](classes/stitch.html#initializedefaultappclient) to initialize the Stitch SDK. Replace `<your-client-app-id>` with your Stitch application's client app ID:

```javascript
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](https://stitch.mongodb.com).

#### Logging In

1. We enabled [anonymous authentication](https://docs.mongodb.com/stitch/authentication/anonymous/) in the steps above, so let's log in with it! Add the following anywhere in your code:

```javascript
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](interfaces/stitchauth.html) for more information.


#### Executing a Stitch Function

One of Stitch's powerful features is serverless [Functions](https://docs.mongodb.com/stitch/functions/). Once logged in, the Stitch client can execute remote Stitch Functions using the [StitchAppClient.callFunction](interfaces/stitchappclient.html#callfunction) method:

```javascript
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:

```javascript
// echoArg Function in the Stitch UI
exports = function(arg) {
  return {arg: arg};
};
```

#### Using BSON and Extended JSON

As a convenience, the SDK includes the [bson](https://www.npmjs.com/package/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:

```javascript
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:

```html
<!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:

```bash
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:

```html
<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:

```javascript
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:

```javascript
const client = Stitch.getAppClient("<your-client-app-id>");
```

---
_Source: https://npm.io/package/mongodb-stitch-browser-sdk · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
