DOM (Front-end) Package

The Memberstack DOM package makes it easy to add Memberstack to any app that runs in a browser environment.

Welcome to the Memberstack DOM package. This package is designed to simplify the process of integrating Memberstack into any browser-based application. For expanded capabilities, please consider our Admin API and React Package.

Getting Started

If you're transitioning from MS 1.0, we recommend reading our guide on how to Convert 1.0 front-end API code to 2.0 code to ensure a smooth transition.

You can install the Memberstack DOM package from either the npm public registry or yarn.

npm:

npm install @memberstack/dom

yarn:

yarn add @memberstack/dom

Initializing the Memberstack Instance

If you're using Webflow, you will first need to define a Memberstack variable as follows:

const memberstack = window.$memberstackDom

Once the package has been successfully installed, you can initialize the Memberstack instance by providing the necessary initialization object.

First, import the Memberstack DOM:

import memberstackDOM from "@memberstack/dom";

Next, initialize your Memberstack instance with your public key:

const memberstack = memberstackDOM.init({
  publicKey: "pk_...",
});

Now your Memberstack instance is ready to use! Continue reading for more details on how to utilize the various features and functionality that this package provides.

Interacting with Pre-built Modals

The DOM package enables seamless interaction with Memberstack's pre-configured modals for login, signup, and password recovery. These interactions are facilitated through the openModal and hideModal methods.

For those utilizing Typescript, the data object type is automatically adjusted based on the selected modal type. If you're a React user, consider using the useMemberstackModal hook to streamline your process.

Please be aware that these pre-built modals are not compatible with live mode in an HTTP environment. Ensure that you're operating under a secure connection (HTTPS) when transitioning to live mode. However, for testing purposes, you can employ the sandbox mode within an HTTP environment.

Open Modals

The DOM package allows you to open various types of modals. Below are the simple commands to open each modal:

Logging In:

To open the login modal, use the following command.

memberstack.openModal("LOGIN");

Login with Signup link:

This option lets you add a signup button at the bottom of the login modal. Note that only free plan IDs are applicable here.

memberstack.openModal("LOGIN", {
signup: {
    plans:["freePlan1", "freePlan2"] //replace with your free plan ids
  }
});

Forgot password:

To open the "Forgot Password" modal, use the following command.

memberstack.openModal("FORGOT_PASSWORD");

Reset password (token modal):

To open the "Reset Password" modal, use the following command.

memberstack.openModal("RESET_PASSWORD");

Profile:

To open the profile modal, use the following command.

memberstack.openModal("PROFILE");

Signup:

To open the signup modal, use this command. If no planId is provided, the new member will be signed up without a plan. As with the login modal, only free plan IDs apply here.

Remember to replace "freePlan1" and "freePlan2" with the actual IDs of your free plans.

memberstack.openModal("SIGNUP", {
signup: {
    plans:["freePlan1", "freePlan2"] //replace with your free plan ids
  }
});
Hide/Close Modals

Modals that you've opened using the DOM package do not automatically close once you're done with them. If you wish to close a modal programmatically, you can do so with the following command:

memberstack.hideModal()

Let's say, for example, you want to close the login modal after a user has completed the login process. You can achieve this by calling the hideModal function after the login form has been submitted.

async function openLoginModal() {
  // Open the login modal
  await memberstack.openModal("LOGIN").then((data) => {
    // Once the login modal has been successfully interacted with,
    // the .then() block will execute.
    // You can use 'data' to access any data returned upon login.

    // Because the pre-built modals do not close automatically,
    // we call memberstack.hideModal() to close it.
    memberstack.hideModal();
  })
}

In this function, we are opening the login modal and waiting for it to return data (e.g., upon successful login). Once the data is returned, we programmatically close the modal.

Return Data From Modals

The DOM package enables you to easily access data returned from signup and login events. When these events complete, the modal returns a promise which resolves with an object containing type and data.

The type field provides the type of the event (either "LOGIN" or "SIGNUP"), and the data field provides additional information associated with the event.

Here are some examples to illustrate this:

Example for Login:

memberstack.openModal("LOGIN").then(({ data, type }) => {
  // Use the 'data' and 'type' variables as needed
  console.log("Login event type:", type);
  console.log("Returned data:", data);
});

Example for Signup:

memberstack.openModal("SIGNUP", {signup: {...}})
.then(({ data, type }) => {
  // Use the 'data' and 'type' variables as needed
  console.log("Signup event type:", type);
  console.log("Returned data:", data);
});

Application

Retrieving App Data

The getApp function allows you to retrieve information about your application. This information is returned in a structured format called an App object.

Example Request:

let appData = memberstack.getApp();

Response Structure:

The getApp function returns a promise with an App object, which is structured as follows:

  • id: The unique identifier for your application.

  • name: The name of your application.

  • mode: The operational mode of your application (e.g., "sandbox").

  • plans: An array of the plans available for your application. Each plan object includes:

    • id: The unique identifier for the plan.

    • name: The name of the plan.

    • description: A brief description of the plan.

    • priority: The priority of the plan.

    • prices: An array of pricing options for the plan. Each price object includes:

      • id: The unique identifier for the price.

      • amount: The cost associated with the price.

      • interval: The billing interval for the price (e.g., "YEARLY").

      • name: The name of the price.

      • type: The type of the price (e.g., "SUBSCRIPTION").

      • status: The status of the price (e.g., "ACTIVE").

      • currency: The currency of the price (e.g., "usd").

  • customFields: An array of custom fields associated with your application. Each custom field object includes:

    • order: The display order of the custom field.

    • label: The label of the custom field.

    • key: The key of the custom field.

    • hidden: A boolean indicating whether the custom field is hidden.

  • captchaRequired: A boolean indicating whether captcha is required.

  • authProviders: An array of authentication providers for your application. Each authentication provider object includes:

    • provider: The name of the authentication provider.

    • icon: The icon for the authentication provider.

    • name: The display name of the authentication provider.

  • additionalAuthMethods: Additional authentication methods available for your application.

  • branding: Branding options for your application, including:

    • logo: The logo for your application.

    • colors: The color scheme for your application.

Example Response:

{
  "data": {
    "id": "app_clbmbs0sd00ao0ugi8nlfdjb6",
    "name": "Import Demo",
    "mode": "sandbox",
    ...
  }
}

In this example, the application's ID is "app_clbmbs0sd00ao0ugi8nlfdjb6", the name is "Import Demo", and it's operating in "sandbox" mode. The ... indicates that there's more data in the response. This could include information about plans, custom fields, authentication providers, and so on, as described in the response structure above.

Retrieving a Specific Plan

The getPlan function allows you to retrieve information about a specific plan in your application.

Example Request:

let planData = memberstack.getPlan({
  planId: "pln_..."
});

Parameters:

  • planId (required): This is the unique identifier (id) of the Plan you want to retrieve. This ID should be a string.

Response Structure:

The getPlan function returns a promise with a Plan object, which is structured as follows:

  • id: The unique identifier for the plan.

  • name: The name of the plan.

  • description: A brief description of the plan.

  • prices: An array of pricing options for the plan. Each price object includes:

    • id: The unique identifier for the price.

    • amount: The cost associated with the price.

    • name: The name of the price.

    • type: The type of the price (e.g., "ONETIME").

    • currency: The currency of the price (e.g., "usd").

    • interval: The billing interval for the price. This will be null for one-time prices.

    • freeTrial: Details about any free trial associated with the price. This will be null if there is no free trial.

    • setupFee: Information about any setup fees associated with the price. Each setup fee object includes:

      • amount: The cost of the setup fee.

      • name: The name of the setup fee.

Example Response:

{
  data: {
    id: "pln_...",
    name: "Premium Plan",
    description: "Get access to all workouts",
    prices: [
      {
        id: "prc_...",
        amount: 1000,
        name: "One Time $100",
        type: "ONETIME",
        currency: "usd",
        interval: null,
        freeTrial: null,
        setupFee: {
          amount: 400,
          name: "Setup Fee"
        }
      },
      { ... },
      { ... }
    ]
  }
}

In this example, the requested plan's ID is "pln_...", the name is "Premium Plan", and it provides access to all workouts. The plan has multiple prices, one of which is a one-time $100 payment. The ... indicates that there are more price options in the response.

Retrieving All Plans

The getPlans function allows you to retrieve information about all the plans in your application.

Example Request:

let allPlans = memberstack.getPlans();

Response Structure:

The getPlans function returns a promise with an array of Plan objects. Each Plan object includes:

  • id: The unique identifier for the plan.

  • name: The name of the plan.

  • description: A brief description of the plan.

  • prices: An array of pricing options for the plan. Each price object includes:

    • id: The unique identifier for the price.

    • amount: The cost associated with the price.

    • name: The name of the price.

    • type: The type of the price (e.g., "ONETIME").

    • currency: The currency of the price (e.g., "usd").

    • interval: The billing interval for the price. This will be null for one-time prices.

    • freeTrial: Details about any free trial associated with the price. This will be null if there is no free trial.

    • setupFee: Information about any setup fees associated with the price. Each setup fee object includes:

      • amount: The cost of the setup fee.

      • name: The name of the setup fee.

Example Response:

{
  data: [
    {
      id: "pln_1...",
      name: "Plan 1",
      description: "Description for Plan 1",
      prices: [ /* array of price objects */ ]
    },
    {
      id: "pln_2...",
      name: "Plan 2",
      description: "Description for Plan 2",
      prices: [ /* array of price objects */ ]
    },
    // ... more plans ...
  ]
}

In this example, the response includes two plans. The first plan's ID is "pln_1...", and the second plan's ID is "pln_2...". Each plan has its own name, description, and array of prices. The ... indicates that there may be more plans in the response.

Authentication

with Email and Password:

Signing Up a Member Using Email and Password

The signupMemberEmailPassword method allows you to create new member accounts using their email and password. Please note that only free plans or no plans can be added during signup. If you want to add a paid plan, you need to create the member account first and then follow the instructions in the "Checkout & Billing" section.

Example Request:

let signupResult = await memberstack.signupMemberEmailPassword({
  email: "john@doe.com",
  password: "123123123",
  customFields: {
    country: "Germany"
  },
  metaData: {
    avatar: "photo.png"
  },
  plans: [
    {
      planId: "pln_..." // Free plan only
    }
  ]
});

Parameters:

  • email (required): The new member's email address.

  • password (required): The new member's password.

  • customFields: Optional additional fields, such as the member's country.

  • metaData: Optional metadata associated with the member.

  • plans : An array of free plans that the member is signing up for. Each item in the array is an object with a planId property indicating the ID of the free Plan.

Response Structure:

The signupMemberEmailPassword method returns a promise with an object containing two properties:

  • member: The newly created Member object, including the member's id, auth information, customFields, metaData, permissions, and planConnections.

  • tokens: An object containing the new member's access token information, including the accessToken, type, and expires timestamp.

Example Response:

{
  member: {
    id: "mem_...",
    auth: {
      email: "john@doe.com"
    },
    customFields: {
      country: "Germany"
    },
    metaData: {
      avatar: "photo.png"
    },
    permissions: ["view:basic:workouts", "view:all:workouts"],
    planConnections: [
      {
        id: "con_...",
        status: "ACTIVE",
        planId: "pln_...",
        type: "FREE",
        payment: null
      },
    ]
  },
  tokens: {
    accessToken: "ey_....389",
    type: "bearer",
    expires: 1631724952366
  }
}

In this example, the new member's id is "mem_...", their email is "john@doe.com", and they're signed up for the free plan with ID "pln_...". Their access token is "ey_....389", and it's a bearer token that expires at the timestamp 1631724952366.

Logging In a Member Using Email and Password

The loginMemberEmailPassword method allows your existing members to log in using their email address and password.

Example Request:

try {
  let loginResult = await memberstack.loginMemberEmailPassword({
    email: "john@doe.com",
    password: "123123123"
  });
} catch (error) {
  // handle error here
}

Parameters:

  • email (required): The member's email address.

  • password (required): The member's password.

Response Structure:

The loginMemberEmailPassword method returns a promise with an object containing two properties:

  • member: The logged-in Member object, including the member's id, auth information, customFields, metaData, permissions, and planConnections.

  • tokens: An object containing the member's access token information, including the accessToken, type, and expires timestamp.

To capture any potential errors during the login process, we recommend wrapping the loginMemberEmailPassword method call in a try-catch block. This allows you to handle errors gracefully and present appropriate feedback to the user.

Example Response:

{
  data: {
    member: {
      id: "mem_...",
      auth: {
        email: "john@doe.com",
        hasPassword: true,
        providers: []
      },
      customFields: {
        country: "Germany"
      },
      metaData: {
        avatar: "photo.png"
      },
      permissions: ["view:basic:workouts", "is:admin"],
      planConnections: [
        {
          id: "con_...",
          status: "ACTIVE",
          planId: "pln_...",
          type: "FREE",
          payment: null
        },
      ]
    },
    tokens: {
      accessToken: "ey_....389",
      type: "bearer",
      expires: 1631724952366
    }
  }
}

In this example, the logged-in member's id is "mem_...", their email is "john@doe.com", and they're part of the free plan with ID "pln_...". Their access token is "ey_....389", and it's a bearer token that expires at the timestamp 1631724952366.

with Passwordless:

Signing Up a Member Using Passwordless Authentication

Passwordless authentication lets your users create accounts without needing to remember a password. It's a two-step process: first, sending a passwordless email, and then, signing up the member using the received token.

Step 1: Send Passwordless Email

This function sends the member an email containing a unique passwordlessToken.

Request Example:

try {
  let emailResult = await memberstack.sendMemberSignupPasswordlessEmail({
    email: "member@member.com"
  });
} catch (error) {
  // handle error here
}

Response:

The function will return a success status if the email was sent successfully.

Response Example:

{
  data: {
    success: true
  }
}

Step 2: Sign Up the Member Without a Password

After the member receives their passwordlessToken via email, you'll prompt them to enter it. This token is then passed to the signupMemberPasswordless function to complete the signup.

Request Example:

try {
  let signupResult = await memberstack.signupMemberPasswordless({
    passwordlessToken: "373822",
    email: "john@doe.com",
    customFields: {
      country: "Germany"
    },
    metaData: {
      avatar: "photo.png"
    },
    plans: [
      {
        planId: "pln_..." // Free plan only
      }
    ]
  });
} catch (error) {
  // handle error here
}

Parameters:

  • passwordlessToken (required): The passwordless token sent to the member’s email.

  • email (required): The member's email (this must match the email to which the token was sent).

  • customFields (optional): Any custom fields you want to associate with the member.

  • metaData (optional): Any metadata you want to associate with the member.

  • plans (required): A list of free plans for which the member is signing up.

Response:

The signupMemberPasswordless method returns a promise with an object containing two properties:

  • member: The Member object, including details such as the member's id, auth information, customFields, metaData, permissions, and planConnections.

  • tokens: An object containing the member's access token information, including the accessToken, type, and expires timestamp.

Example Response:

{
  member: {
    id: "mem_...",
    auth: {
      email: "john@doe.com",
      hasPassword: false,
      providers: []
    },
    customFields: {
      country: "Germany"
    },
    metaData: {
      avatar: "photo.png"
    },
    permissions: ["view:basic:workouts", "view:all:workouts"],
    planConnections: [
      {
        id: "con_...",
        status: "ACTIVE",
        planId: "pln_...",
        type: "FREE",
        payment: null
      },
    ]
  },
  tokens: {
    accessToken: "ey_....389",
    type: "bearer",
    expires: 1631724952366
  }
}
Logging in a Member Using Passwordless Authentication

Passwordless authentication enables your members to log in without needing to remember a password. This is a two-step process involving sending a passwordless email and then logging in the member using the received token.

Step 1: Send Passwordless Email

This function sends the member an email containing a unique passwordlessToken.

Request Example:

try {
  let emailResult = await memberstack.sendMemberLoginPasswordlessEmail({
    email: "member@member.com"
  });
} catch (error) {
  // handle error here
}

Response:

The function will return a success status if the email was sent successfully.

Response Example:

javascriptCopy code{
  data: {
    success: true
  }
}

Step 2: Log In the Member Without a Password

After the member receives their passwordlessToken via email, you'll prompt them to enter it. This token is then passed to the loginMemberPasswordless function to complete the login.

Request Example:

try {
  let loginResult = await memberstack.loginMemberPasswordless({
    passwordlessToken: "373822",
    email: "john@doe.com"
  });
} catch (error) {
  // handle error here
}

Parameters:

  • passwordlessToken (required): The passwordless token sent to the member’s email.

  • email (required): The member's email (this must match the email to which the token was sent).

Response:

The loginMemberPasswordless method returns a promise with an object containing two properties:

  • member: The Member object, including details such as the member's id, auth information, customFields, metaData, permissions, and planConnections.

  • tokens: An object containing the member's access token information, including the accessToken, type, and expires timestamp.

Example Response:

{
  member: {
    id: "mem_...",
    auth: {
      email: "john@doe.com",
      hasPassword: false,
      providers: []
    },
    customFields: {
      country: "Germany"
    },
    metaData: {
      avatar: "photo.png"
    },
    permissions: ["view:basic:workouts", "view:all:workouts"],
    planConnections: [
      {
        id: "con_...",
        status: "ACTIVE",
        planId: "pln_...",
        type: "FREE",
        payment: null
      },
    ]
  },
  tokens: {
    accessToken: "ey_....389",
    type: "bearer",
    expires: 1631724952366
  }
}

In this example, the member's id is "mem_...", their email is "john@doe.com", and they're part of the free plan with ID "pln_...". Their access token is "ey_....389", and it's a bearer token that expires at the timestamp 1631724952366.

Setting a Password for a Member (Only used if the member has no password)

The setPassword function allows a member to establish a password for their account, typically after signing up using a passwordless method. This could be useful if you'd like the member to set a password after initially signing up without one.

Request Example:

try {
  let passwordResult = await memberstack.setPassword({
    password: "supersecretpassword"
  });
} catch (error) {
  // handle error here
}

Parameter:

  • password (required): The new password the member wants to set.

Response:

The setPassword method returns a promise with an object containing two properties:

  • member: The Member object, including details such as the member's id, auth information, customFields, metaData, permissions, and planConnections.

  • tokens: An object containing the member's access token information, including the accessToken, type, and expires timestamp.

Now, the hasPassword attribute within the auth object would be set to true, indicating that the member has set a password.

Example Response:

{
  member: {
    id: "mem_...",
    auth: {
      email: "john@doe.com",
      hasPassword: true,
      providers: [{
        provider: "google"
      }]
    },
    customFields: {
      country: "Germany"
    },
    metaData: {
      avatar: "photo.png"
    },
    permissions: ["view:basic:workouts", "view:all:workouts"],
    planConnections: [
      {
        id: "con_...",
        status: "ACTIVE",
        planId: "pln_...",
        type: "FREE",
        payment: null
      },
    ]
  },
  tokens: {
    accessToken: "ey_....389",
    type: "bearer",
    expires: 1631724952366
  }
}

In this example, the member's id is "mem_...", their email is "john@doe.com", and they're part of the free plan with ID "pln_...". Their access token is "ey_....389", and it's a bearer token that expires at the timestamp 1631724952366. After the password is set, the hasPassword attribute in the auth object is now true.

with Auth Providers:

Signing up a Member with an Authentication Provider

This functionality allows members to create accounts using a configured authentication provider, such as Google or Facebook. This streamlines the signup process by using existing credentials from these providers, increasing user convenience and potentially improving conversion rates for signups.

Request Example:

try {
  let signupResult = await memberstack.signupWithProvider({
    provider: "facebook",
    customFields: {
      country: "Germany"
    },
    plans: [
      {
        planId: "pln_...", // Free plan only
      },
    ]
  });
} catch (error) {
  // handle error here
}

Parameters:

  • provider (required): The authentication provider that will be used. This can be either google or facebook.

  • customFields (optional): Any custom fields that you want to associate with the member.

  • plans (optional): An array of free plans that the member is signing up for. Each plan should be an object with a planId property. If left blank, the member will have no plan.

Response:

The signupWithProvider method returns a promise with an object that includes the following:

  • member: The Member object, containing details about the member such as their id, auth information, customFields, metaData, permissions, and planConnections.

  • tokens: An object containing the member's access token information, including the accessToken, refreshToken, type, and expires timestamp.

Example Response:

{
  member: {
    id: "mem_...",
    auth: {
      email: "john@doe.com",
      hasPassword: false,
      providers: [{ provider: "google" }]
    },
    customFields: {
      country: "Germany"
    },
    metaData: {
      avatar: "photo.png"
    },
    permissions: ["view:basic:workouts", "view:all:workouts"],
    planConnections: [
      {
        id: "con_...",
        status: "ACTIVE",
        planId: "pln_...",
        type: "FREE",
        payment: null
      },
      // ... more plan connections can be listed here
    ]
  },
  tokens: {
    accessToken: "ey_....389",
    refreshToken: "29ke....1992",
    type: "bearer",
    expires: 1631724952366
  },
  payment: {
    requireAuthentication: [],
    requirePayment: [],
    failedPayment: []
  }
}

In this example, the member's id is "mem_...", their email is "john@doe.com", and they're part of the free plan with ID "pln_...". Their access token is "ey_....389", and it's a bearer token that expires at the timestamp 1631724952366. The providers array within the auth object shows that the member used Google as their authentication provider.

Logging in a Member with an Authentication Provider

This feature allows your members to log in using an authentication provider, such as Google or Facebook. This simplifies the login process by leveraging existing credentials from these providers, improving user convenience.

Request Example:

javascriptCopy codetry {
  let loginResult = await memberstack.loginWithProvider({
    provider: "google"
  });
} catch (error) {
  // handle error here
}

Parameters:

  • provider (required): The authentication provider to be used. This can be either google or facebook.

Response:

The loginWithProvider method returns a promise with an object that includes the following:

  • member: The Member object, containing details about the member such as their id, auth information, customFields, metaData, permissions, and planConnections.

  • tokens: An object containing the member's access token information, including the accessToken, type, and expires timestamp.

Example Response:

javascriptCopy code{
  data: {
    member: {
      id: "mem_...",
      auth: {
        email: "john@doe.com",
        hasPassword: false,
        providers: [{ provider: "google" }]
      },
      customFields: {
        country: "Germany"
      },
      metaData: {
        avatar: "photo.png"
      },
      permissions: ["view:basic:workouts"],
      planConnections: [
        {
          id: "con_...",
          status: "ACTIVE",
          planId: "pln_...",
          type: "FREE",
          payment: null
        }
      ]
    },
    tokens: {
      accessToken: "ey_....389",
      type: "bearer",
      expires: 1631724952366
    }
  }
}

In this example, the member's id is "mem_...", their email is "john@doe.com", and they're part of the free plan with ID "pln_...". Their access token is "ey_....389", and it's a bearer token that expires at the timestamp 1631724952366. The providers array within the auth object shows that the member used Google as their authentication provider.

Linking an Authentication Provider

This section shows you how to link an authentication provider such as Google or Facebook using Memberstack's front-end package.

Request Example:

Here's a quick example of how to execute this request:

await memberstack.connectProvider({
  provider: "google"
})

Parameters:

  • provider (required, string): This is the key of the provider you want to connect. It could be "google", "facebook", etc.

Response:

  • data (object): This contains a list of providers to which the member is currently connected.

Response Example:

Here's an example of what the response might look like:

javascriptCopy code{
  data: {
    providers: [{
      provider: "google"
    }]
  }
}

In this response, it shows that the member is connected to Google as an authentication provider.

Unlinking an Authentication Provider

This section demonstrates how to unlink an authentication provider, like Google or Facebook, using Memberstack's front-end package.

Request Example:

Here's how to execute this request.

javascriptCopy codeawait memberstack.disconnectProvider({
  provider: "google"
})

Parameters:

  • provider (required, string): This is the key of the provider you want to disconnect. Options include "google", "facebook", etc.

Response:

  • data (object): This contains a list of providers that the member is still connected to after the disconnection.

Response Example:

Here's a sample response.

javascriptCopy code{
  data: {
    providers: [{
      provider: "google"
    }]
  }
}

This response indicates that the member remains connected to Google, suggesting that the disconnection request was not successful. Always ensure that the disconnected provider is not listed in the response.

Password Management:

Send Reset Password Email

This section guides you on how to send a password reset email to a member using Memberstack's DOM (front-end) package.

Request Example:

Here's how to trigger a password reset email.

await memberstack.sendMemberResetPasswordEmail({
  email: "john@doe.com",
})

Parameters:

  • email (required, string): The email address of the member who needs to reset their password.

Response:

  • data (string): A message indicating that if the provided email exists in the system, a reset password email has been sent.

Response Example:

Here's a sample response.

{
  data: "If this email exists, we sent you an email with the reset instructions."
}

This response does not confirm whether the password reset email was sent, to protect user privacy. It merely suggests that if the given email is associated with an existing Memberstack account, the email has been sent.

Reset Password

Allows a member to reset their password based on the received token.

Request Example:

await memberstack.resetMemberPassword({
  token: "...",
  newPassword: "..."
})

Parameters:

  • token required string The reset token that was sent to the member's email.

  • newPassword required string The member's new password.

Response:

  • data object A success property indicating if the password reset was successful.

Example Response:

{
  data: {
    success: true
  }
}
Logout

Allows a member to log out of their account.

Request Example:

await memberstack.logout()

Response:

  • data string The logged out member's id.

Response Example:

{
  data: {
   id: "mem_sb_clgdzx8ba001v0sg02gu9bypk"
  }
}

Auth Change Listeners:

Auth State Change Listeners

This guide explains how to track changes in authentication status, such as signup, login, and logout, for a currently authenticated member with Memberstack's front-end package.

⚠️ Note: This functionality is only available in the @memberstack/dom and @memberstack/react packages.

Request Example:

You can utilize the onAuthChange method to observe authentication state changes. Here's an illustrative example:

memberstack.onAuthChange(member => {
  if (member) {
    console.log("Member is authenticated. Member details:", member);
  } else {
    console.log("Member is not authenticated");
  }
})

This method yields an object that allows you to unsubscribe the current listener. After unsubscribing, Memberstack will stop sending authentication updates to the callback function.

const listener = memberstack.onAuthChange(data => {
  console.log("Authentication state changed. New data:", data);
})

// When updates are no longer needed, you can unsubscribe
listener.unsubscribe()

listener.unsubscribe() is crucial for a few reasons:

  1. Resource Efficiency: Unsubscribing frees up system resources, keeping your application running smoothly.

  2. Preventing Memory Leaks: Forgetting to unsubscribe can lead to unused data filling up memory over time, slowing down or crashing your application.

  3. Control: It allows you to dictate when to stop receiving updates, useful when certain conditions in your app are met.

For instance, in a single-page app, you might set up a listener to monitor user logins on the home page. When the user leaves the home page, use listener.unsubscribe() to stop monitoring and free up resources.

Parameters:

  • callback (function): The callback function that is invoked when the authentication state changes. This function should be prepared to handle both authenticated member objects and null values.

Response:

  • Returns an object or null: If a member is authenticated, the Member object is returned. If no member is authenticated, null is returned.

Checkout & Billing

Note that parameters with ? are optional. Parameters without ? are required.

Checkout:

Purchase Plans With Checkout

This function is used to initiate the purchase process for a specific plan with a checkout flow. It requires a priceId which corresponds to the plan you'd like the member to purchase.

Request Example:

In this example, priceId is a required parameter that identifies the price of the plan to be purchased. The other parameters are optional and have default values.

await memberstack.purchasePlansWithCheckout({
  priceId: "prc_123", // required
  cancelUrl?: string,
  successUrl?: string,
  autoRedirect?: boolean,
})

Request Example with Signup:

This example demonstrates how to first sign up a member and then redirect them to the Stripe checkout for plan purchase.

try {
  // first signup the member
  await memberstack.signupMemberEmailPassword({
    email: "member@test.com",
    password: "supersecretpassword"
  })

  // or if using signup modal
  await memberstack.openModal("SIGNUP")

  // after successful signup, redirect them to the stripe checkout
  await memberstack.purchasePlansWithCheckout({
    priceId: "prc_123", // required
    cancelUrl?: string,
    successUrl?: string,
    autoRedirect?: boolean,
  })
} catch(err) {
  displayErrorMessage(err.message) // email already taken, etc.
}

Parameters:

  • priceId (required): Identifier for the price of the plan that the member will purchase.

  • cancelUrl (optional): URL to redirect to if the user cancels the checkout process. Defaults to the current page if not specified.

  • successUrl (optional): URL to redirect to after a successful purchase. Defaults to the current page if not specified.

  • autoRedirect (optional): If set to true, the user will be automatically redirected to the Stripe checkout or the cancelUrl/successUrl as appropriate. If false, the function will return the Stripe checkout URL instead. Defaults to true if not specified.

Response:

If autoRedirect is set to false, purchasePlansWithCheckout will return the stripe checkout URL.

{
  data : {
    url: "https://checkout.stripe.com/c/pay/..."
  }
}

Billing:

Launch Stripe Customer Billing Portal

Request Example:

await memberstack.launchStripeCustomerPortal({ 
  priceIds?: string[],
  configuration?: object,
  returnUrl?: string,
  autoRedirect?: boolean,
})

Example with Configuration - e.x. the following would launch the billing portal and only display the invoice history

await memberstack.launchStripeCustomerPortal({
    configuration: {
      invoice_history: {
        enabled: true,
      },
    },
  });

Parameters:

  • priceIds required Provide the price IDs that should be included in the billing portal if a member wishes to update their plan. Without a priceId the button for the plan will say "cancel".

  • configuration optional

    You can use the configuration param in order to use your own stripe billing portal features object. Stripe docs here.

  • cancelUrl optional default current page

  • successUrl optional default current page

  • autoRedirect optional default true

Response:

If autoRedirect is set to false, launchStripeCustomerPortal will return the stripe billing portal URL.

{
  data : {
    url: "https://billing.stripe.com/p/session/..."
  }
}

Member Management

Get Current Member

Get the currently logged in member.

Request Example:

await memberstack.getCurrentMember()

Response:

  • data object The Member object or null if there’s no member.

Response Example:

{
  data: {
    id: "mem...",
    createdAt: "2022-05-19T18:57:35.143Z",
    lastLogin: "2022-06-19T18:57:35.143Z",
    auth: {
      email: "john@doe.com",
      hasPassword: true,
      providers: []
    },
    customFields: {
      country: "Germany"
    },
    metaData: {
      avatar: "photo.png"
    },
    permissions: ["view:basic:workouts"],
    planConnections: [
      {
        id: "con_...",
        status: "ACTIVE"
        planId: "pln_...",
        type: "FREE",
        payment: null
      },
    ],
    verified: true
  }
}
Update Current Member Custom Fields

Allows you to update the custom field on a member. This does not update the member login redirect.

Request Example:

await memberstack.updateMember({
    customFields: {
      country: "Canada"
    }
})

Parameters:

  • customFields object An object containing custom fields. The object's keys should be the custom fields key.

Response:

  • data object The Member object

Response Example:

{
  data: {
    id: "mem...",
    auth: {
      email: "john@doe.com"
    }
    customFields: {
      country: "Canada"
    },
    metaData: {
      age: 24
    },
    permissions: ["view:basic:workouts"],
    planConnections: [
      {
        id: "con_...",
        status: "ACTIVE"
        planId: "pln_...",
        type: "FREE",
        payment: null
      },
    ]
  }
}
Update Current Member Email

Allows you to update a member's email.

Request Example:

await memberstack.updateMemberAuth({
  email: "johndoe+newemail@gmail.com"
})

Parameters:

  • email required string The member's new email

Response:

  • data object The Member object

Response Example:

{
  data: {
    id: "mem...",
    auth: {
      email: "johndoe+newemail@gmail.com"
    }
    customFields: {
      country: "Germany"
    },
    metaData: {
      avatar: "photo.png"
    },
    permissions: ["view:basic:workouts"],
    planConnections: [
      {
        id: "con_...",
        status: "ACTIVE"
        planId: "pln_...",
        type: "FREE",
        payment: null
      },
    ]
  }
}
Update Current Member Password

Allows you to update a member's password.

Request Example:

await memberstack.updateMemberAuth({
   oldPassword: "...",
   newPassword: "..."
})

Parameters:

  • oldPassword required string The member's current password

  • newPassword required string The member's new password

Response:

  • data object The Member object

Response Example:

{
  data: {
    id: "mem...",
    auth: {
      email: "johndoe@gmail.com"
    }
    customFields: {
      country: "Germany"
    },
    metaData: {
      avatar: "photo.png"
    },
    permissions: ["view:basic:workouts"],
    planConnections: [
      {
        id: "con_...",
        status: "ACTIVE"
        planId: "pln_...",
        type: "FREE",
        payment: null
      },
    ]
  }
}
Send Member Verification Email

Send or resend the member a verification email.

Request Example:

await memberstack.sendMemberVerificationEmail()

Response:

  • data object The success property indicating if the email was successfully sent.

Response Example:

{
  data: {
    success: true
  }
}
Get Current Member JSON

Retrieve the JSON object containing information about the currently logged-in member.

Request Example:

await memberstack.getMemberJSON();

Response:

  • data object The JSON object representing the member's information.

Response Example:

{
  data: {
    username: "josh",
    location: {
      city: "Butte",
      state: "Montana"
    },
    skills: ["graphql", "react", "tailwindcss"],
  }
}
Update Current Member JSON

This function updates the JSON data for the currently logged-in member. If an authenticated member is available, Memberstack will return the updated JSON for that member.

For best practices, we suggest first retrieving the current member's JSON using await memberstack.getMemberJSON(). Then, make necessary changes before applying the update. This approach ensures all existing data is preserved while new data is added or existing data is modified.

Request Example:

// Get current member's JSON
let memberJson = await memberstack.getMemberJSON();

// Modify or add new data
memberJson.avatarURL = "https://www.media.com/buckets/josh/avatar.jpg";

// Remove data
delete memberJson.skills;

// Update member's JSON
await memberstack.updateMemberJSON({json: memberJson});

In this example, the avatarURL has been added to the existing member's JSON and we've removed the skills property from the member's JSON data. The delete keyword in JavaScript is used to remove a property from an object. Note that this will permanently remove the skills property from the member's JSON, so make sure this is the intended action before executing the code.

Response:

  • data object The updated Member JSON object.

Response Example:

{
  data: {
    username: "josh",
    avatarURL: "https://www.media.com/buckets/josh/avatar.jpg",
    location: {
      city: "Butte",
      state: "Montana"
    },
    // skills: ["graphql", "react", "tailwindcss"], this was removed
  }
}
Add Logged-in Member Free Plan

Add free plans to a member.

Request Example:

await memberstack.addPlan({
  planId: "pln_abc"
})

Response:

{
  data: {
    member: {
      id: "mem...",
      createdAt: "2022-05-19T18:57:35.143Z",
      lastLogin: "2022-06-19T18:57:35.143Z",
      auth: {
        email: "john@doe.com",
        hasPassword: true,
	providers: []
      },
      customFields: {
        country: "Germany"
      },
      metaData: {
        avatar: "photo.png"
      },
      permissions: ["view:basic:workouts"],
      planConnections: [{
        id: "con_...",
        status: "ACTIVE",
        planId: "pln_...",
        type: "FREE",
        payment: null
      }],
      verified: true
    }
  }
}
Remove Logged-in Member Free Plan

Request Example:

await memberstack.removePlan({
	planId: "pln_abc"
})

Response:

{
  data: {
    member: {
      id: "mem...",
      createdAt: "2022-05-19T18:57:35.143Z",
      lastLogin: "2022-06-19T18:57:35.143Z",
      auth: {
        email: "john@doe.com",
        hasPassword: true,
        providers: []
      },
      customFields: {
        country: "Germany"
      },
      metaData: {
        avatar: "photo.png"
      },
      permissions: ["view:basic:workouts"],
      planConnections: [{
        id: "con_...",
        status: "ACTIVE"
        planId: "pln_...",
        type: "FREE",
        payment: null
      }],
      verified: true
    }
  }
}

Events

Webhooks

Listen to events within your application.

You can enable webhooks in the Devtools section in the dashboard.

You can verify incoming webhooks with the [verifySignature] method.

Members:

member.created

Fires after a new member has been created.

Response:

  • event string The type of event

  • timestamp number The time at which the event was fired.

  • payload object The Member object

Response Example:

{
  event: "member.created",
  timestamp: 1633486880169,
  payload: {
    id: "mem_...",
    auth: {
      email: "john@doe.com"
    },
    metaData: { ... },
    customFields: { ... }
  }
}
member.updated

Fires after a member has been updated.

Fires on email change, custom fields, and metadata.

This does not fire on password change.

Response:

  • event string The type of event

  • timestamp number The time at which the event was fired.

  • payload object The Member object

Response Example:

{
  event: "member.updated",
  timestamp: 1633486880169,
  payload: {
    id: "mem_...",
    auth: {
      email: "john@doe.com"
    },
    metaData: { ... },
    customFields: { ... }
  }
}
member.deleted

Fires after a member has been deleted.

Response:

  • event string The type of event

  • timestamp number The time at which the event was fired.

  • payload object An object containing the deleted member's id

Response Example:

{
  event: "member.deleted",
  timestamp: 1633486880169,
  payload: {
    id: "mem_..."
  }
}

Plan Connections:

member.plan.created

Fires after a new plan connection has been created for a member. If using the DOM package this fires once if multiple plans are created at the same time. The plans array would contain all the plans the member signed up for.

V2 allows for multiple plans for members and this fires each time a plan is added to a member.

Response:

  • event string The type of event

  • timestamp number The time at which the event was fired.

  • payload object An object containing the member's id, and the plan connection.

Response Example:

{
  event: "member.planConnection.created",
  timestamp: 1633486880169,
  payload: {
    id: "mem_...",
    planConnection: {
        id: "con_...",
        active: true,
        status: "ACTIVE",
        type: "SUBSCRIPTION",
        planId: "pln_..."
        memberId: "mem_..."
    }
  }
}
member.plan.updated

Fires after a plan connection has been updated, anytime the status of the plan updates, or payment period updates.

Response:

  • event string The type of event

  • timestamp number The time at which the event was fired.

  • payload object An object containing the member's id, and the plan connection.

Response Example:

{
  event: "member.planConnection.updated",
  timestamp: 1633486880169,
  payload: {
    id: "mem_...",
    planConnection: {
        id: "con_...",
        active: true,
        status: "ACTIVE",
        type: "SUBSCRIPTION",
        planId: "pln_..."
        memberId: "mem_..."
    }
  }
}
member.plan.canceled

Fires when a member cancels a plan.

Response:

  • event string The type of event.

  • timestamp number The time at which the event was fired.

  • payload object An object containing the member's id, and the canceled plan connection id.

Response Example:

{
  event: "member.planConnection.canceled",
  timestamp: 1633486880169,
  payload: {
    id: "mem_...",
    planConnectionId: "con_..."
  }
}

Last updated