Linking User Accounts

MongoDB Stitch provides multiple ways for you to integrate user authentication into your apps. For this reason, you may want to provide a way for your users to link their account from one provider with another.

For example, suppose you have an app that enables users to authenticate using Google or Facebook, but also allows anonymous log in. New users of your app may explore the app’s functionality as an anonymous user. After working with the app for a while, a user decides to create an account. The user logs in using their Google credentials, and your app can link the data from their anonymous session to their account by using Stitch’s user-linking feature.

To provide user account linking in your code, add your app’s hosted domain to the list of Allowed Request Origins in General Settings and then use the linkWithCredential method of the StitchUser class. Documentation for this method can be found in the SDKs:


// User is logged in with AnonymousCredential
const { user } = client.auth

// After using the app anonymously, the user may decide to create an account.
// The linkWithCredential() and linkUserWithRedirect() methods associate
// the current user with the new user credential.
function linkWithUsernamePasswordAccount(username, password) {
    .linkWithCredential(new UserPasswordCredential(username, password))

function linkWithGoogleAccount() {
    .linkUserWithRedirect(new GoogleRedirectCredential())
// Called when an anonymous user decides to create an account with username and password.
private void linkWithNewUserPasswordUser(String username, String password) {
  // Get the currently logged-in (anonymous) user from Stitch.
  final StitchAuth auth = Stitch.getDefaultAppClient().getAuth();
  final StitchUser user = auth.getUser();

  // Create and link a new account with the given username and password.
  user.linkWithCredential(new UserPasswordCredential(username, password))
    .addOnCompleteListener(new OnCompleteListener<StitchUser>() {
      public void onComplete(@NonNull Task<StitchUser> task) {
        // User is now linked
// import StitchCore

func linkWithNewUsernamePassword(username: String, password: String) {
    // Get the Stitch client and auth.
    let client = Stitch.defaultAppClient!
    let auth = client.auth

    // In this example, we are assuming that there
    // is a currently logged-in anonymous user.
    let user = auth.currentUser!

    // Create a new username and password credential,
    // which we will link with the anonymous user.
    let credential = UserPasswordCredential.init(
        withUsername: username,
        withPassword: password

    // Link the current anonymous user with the new user credential.
    // The completionHandler is passed as a second argument. credential, {(user: StitchResult<StitchUser>) in
        // completionHandler: User is now linked