Navigation

Initialize the StitchAppClient

In each of the MongoDB Stitch SDKs, there is a StitchAppClient class that offers functionality for communicating with the Stitch backend. This functionality includes methods for authentication, executing functions, and accessing services.

Procedure

In the Stitch JavaScript SDK, you can create a StitchAppClient instance using the Stitch.initializeDefaultAppClient() static method.

For a basic web application with vanilla JavaScript and HTML, this could look like the following:

<html>
  <head>
    <script src="https://s3.amazonaws.com/stitch-sdks/js/bundles/4.0.0/stitch.js"></script>
    <script>
      const client = stitch.Stitch.initializeDefaultAppClient('<your-app-id>');
      // perform other application initialization logic here
    </script>
  </head>
  <body onload="initApplication()">
    <h1>My App</h1>
    <div id="content">
      Welcome to my basic application.
    </div>
  </body>
</html>

Replace <your-client-app-id> with your MongoDB Stitch App ID. In the MongoDB Stitch admin console, you can find your App ID in the Clients view.

React

React is a widely used JavaScript library for building user interfaces.

Call the Stitch.initializeDefaultAppClient() static method to initialize the default Stitch client at the start of your application. You may then use the Stitch.defaultAppClient property to interact with Stitch.

For example:

import React from "react";
import { render } from "react-dom";
import { Stitch } from 'mongodb-stitch-browser-sdk'

var YourRootComponent = class extends React.Component {
   render() {
      return (
         <div>
            <NavigationBar/>
            {Stitch.defaultAppClient.auth.isLoggedIn ?
               <Dashboard /> :
               <AuthControls }/>
            }
            <Footer/>
         </div>
      );
   }
};

Stitch.initializeDefaultAppClient('<your-app-id>');
render(
   <YourRootComponent />
)

For a more comprehensive view of how the StitchAppClient can be initialized and used in a React application, view the ToDo Web App tutorial and associated sample code.

StitchAppClient

The Stitch class is the entry point into the Stitch Android API. Using this class, you can instantiate a StitchAppClient instance to interact with Stitch.

You can obtain a StitchAppClient instance in one of two ways:

Default StitchAppClient
Use the static Stitch.getDefaultAppClient() method to obtain the default StitchAppClient initialized at application start using the Stitch App ID specified in your Android application’s strings.xml file.
Custom StitchAppClient

Some users may need to connect to several different Stitch applications, or customize their StitchAppClient instance to use more advanced features of the Stitch SDK.

To do this, you must initialize it using the static Stitch.initializeAppClient() method.

Example

Add the following to your strings.xml resource file:

<!-- app/src/main/res/values/strings.xml -->
<resources>
   <string name="app_name">Stitch Sample Push Notification App</string>
   <string name="stitch_client_app_id">STITCH-APP-ID</string>
</resources>

Replace STITCH-APP-ID with your MongoDB Stitch App ID. In the MongoDB Stitch admin console, you can find your App ID in the Clients view.

The following sample code demonstrates how to add StitchAppClient to an Activity. You should adapt it to fit your application’s architecture.

import com.mongodb.stitch.android.core.auth.StitchUser;
import com.mongodb.stitch.android.core.Stitch;
import com.mongodb.stitch.android.core.StitchAppClient;
import com.mongodb.stitch.core.auth.providers.anonymous.AnonymousCredential;

public class MainActivity extends AppCompatActivity {
    StitchAppClient stitchClient = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.stitchClient = Stitch.getDefaultAppClient();

        Log.d("stitch", "logging in anonymously");
        stitchClient.getAuth().loginWithCredential(new AnonymousCredential()
                ).continueWithTask(new Continuation<StitchUser, Task<Void>>() {
                   @Override
                   public Task<Void> then(@NonNull Task<StitchUser> task) throws Exception {
                       if (task.isSuccessful()) {
                           Log.d("stitch", "logged in anonymously as user " + task.getResult());
                       } else {
                           Log.e("stitch", "failed to log in anonymously", task.getException());
                       }
                   }
               })
    }
}

Warning

When it comes to authentication events such as logging in or logging out, the StitchAppClient class is not thread-safe. If your application can perform authentication events from different threads simultaneously, be sure to use a Lock to protect authentication calls to the StitchAppClient.

StitchAppClient

The Stitch class is the entry point into the Stitch iOS API. Using this class, you can instantiate a StitchAppClient instance to interact with Stitch.

You can obtain a StitchAppClient instance in one of two ways:

Default StitchAppClient

Use the static Stitch.initializeDefaultAppClient method to initialize the default Stitch StitchAppClient client. You should typically call this in the application(_:didFinishLaunchingWithOptions:) method of your project’s AppDelegate.

You can then use the static Stitch.defaultAppClient property.

Custom StitchAppClient

Some users may need to connect to several different Stitch applications, or customize their StitchAppClient instance to use more advanced features of the Stitch SDK.

To do this, you must initialize it using the static Stitch.initializeAppClient() method.

Example

The following sample code demonstrates how to add StitchAppClient to an iOS project. You should adapt it to fit your application’s architecture.

In the application(_:didFinishLaunchingWithOptions:) method of your project’s AppDelegate, you should call Stitch.initializeDefaultAppClient to initialize the Stitch client:

import StitchCore

// ...

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    // ...

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        do {
            _ = try Stitch.initializeDefaultAppClient(withConfigBuilder:
                StitchAppClientConfigurationBuilder.forApp(withClientAppID: "your-client-app-id")
            )
        } catch {
            print("Failed to initialize MongoDB Stitch iOS SDK: \(error.localizedDescription)")
            // note: This initialization will only fail if an incomplete configuration is
            // passed to a client initialization method, or if a client for a particular
            // app ID is initialized multiple times. See the documentation of the "Stitch"
            // class for more details.
        }

        return true
    }

Replace <your-client-app-id> with your MongoDB Stitch App ID. In the MongoDB Stitch admin console, you can find your App ID in the Clients view.

You can then use the static Stitch.defaultAppClient property to authenticate and use the Remote MongoDB Service:

import UIKit
import StitchCore
import StitchRemoteMongoDBService

class ViewController: UIViewController {

    private lazy var stitchClient = Stitch.defaultAppClient!
    private var mongoClient: RemoteMongoClient?

    override func viewDidLoad() {
        mongoClient = stitchClient.serviceClient(fromFactory: remoteMongoDBServiceClientFactory, withName: "mongodb-atlas")

        // Perform any Stitch-dependent initialization here.

        // For example:
        if !stitchClient.isAuthenticated() {
           self.displayAuthControls()
        }

        let credential = AnonymousCredential.init()
        stitchClient.auth.login(withCredential: credential) {result in
            switch result {
            case .success(_):
                // Successful authenticationn
            case .failure(let error):
                print("failed logging in Stitch. error: \(error)")
            }
        })

        // Do any additional setup after loading the view, typically from a nib.
    }
}

Warning

When it comes to authentication events like logging in or logging out, the StitchAppClient class is not thread-safe. If your application can perform authentication events from different threads simultaneously, be sure to use an NSLock to protect authentication calls to the StitchAppClient.

←   Client SDKs Import/Export  →