Vanilla JS Guide

Article author
Memberstack Team
  • Updated

Introduction

There are two different ways to use Memberstack in a vanilla JS environment:

  1. Using @memberstack/dom NPM package
  2. Using the memberstack.js static library

Comparison

The @memberstack/dom package is our core API. It powers our Webflow & React libraries. You’ll need a node development server, build tools and a package manager to install it into your project.

The memberstack.js script is the same exact script we use for Webflow, so you can also opt-in to using the ms-member data-attribute directives. When using memberstack.js from a script tag, there is no need for build tools, package managers or Node development servers.

Use The DOM Package If…

  • You want to use memberstack in a Single Page App framework (SPA)
  • Your project includes node package managers & build tooling
  • You’re using frameworks that require compilation & build steps (Vue SFCs, Svelte Kit, Typescript, etc.)

Use Memberstack.js If…

  • You want to benefit from using our ms-member data-attribute directives.
    • See this doc for a more detailed walkthrough on signup forms with data attributes.
  • You don’t want to use a package manager or involve a “build” step

When using the memberstack.js script, keep these things in mind:

  • The script does not re-initialize itself (consider this if using SPA frameworks with virtual DOMs and lifecycle events)
  • Using auth-related data attributes on login / signup forms will automatically redirect users to any paths you have set in the dashboard
  • You will see a test mode banner at the bottom of your site if you haven’t configured production domains in the dashboard

Quick Start

Using Memberstack From a Static Script

If you prefer working without the added complexity of build tools and package managers, or you want to opt-in to our special memberstack data-attribute directives, you can use memberstack.js directly with a script tag:

<script
  data-memberstack-app="app_..." // your project's APP ID
  src="<https://static.memberstack.com/scripts/v1/memberstack.js>"
  type="text/javascript"
>
</script>

In addition to using our data attributes, you can now access all of the core methods available in our DOM API using the $memberstackDom global variable exposed in the window. You can also override the default amount of days that a session persists.

<html lang="en">
  <head>
    <script
      data-memberstack-app="app_cl92vfop300wr0vjm2q3n4njb"
      src="<https://static.memberstack.com/scripts/v1/memberstack.js>"
      type="text/javascript"
    ></script>
  </head>
  <body>  
    <script> 
      const memberstack = window.$memberstackDom;
      // Session Duration
      ms_session_duration_days = 14 //days
      memberstack.getApp().then(({ data : app }) => console.log({ app }))
    </script>
  </body>
</html>

Installing the DOM package

If you prefer working with frameworks, build tools and package managers, you can install Memberstack DOM from the NPM public registry, or yarn.

Run the following command in your terminal:

npm install @memberstack/dom
#or
yarn add @memberstack/dom

After the package has been installed successfully, you can initialize the Memberstack instance by supplying your public key (found in the dev tools section of the dashboard).

import memberstackDOM from "@memberstack/dom";

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

Besides passing the default initialization object values, the DOM package also allows you to pass a sessionDurationDays field. This allows you to override the default amount of days that a session persists.

import memberstackDOM from "@memberstack/dom";

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

Authentication

  • Signup Examples (without paid plans)
    • Static Signup Example w/ Data Attributes (no JavaScript)

      Using a classic form:

      <!-- memberstack.js script must be installed in <head /> -->
      <body>
        <main>
          <h1>Sign Up</h1>
          <br />
          <form data-ms-form="signup">
            <input name="email" type="text" data-ms-member="email" />
            <input name="password" type="text" data-ms-member="password" />
          </form>
        </main>
      </body>
      

      Using our pre-built UI modals:

      <!-- memberstack.js script must be installed in <head /> -->
      <body>
        <nav>
          <button data-ms-modal="signup">Sign Up</button>
        </nav>
      ...
      
    • Static Signup Example w/ raw JavaScript methods

      <!-- memberstack.js script must be installed in <head /> -->
      <body>
        <main>
          <h1>Sign Up</h1>
          <br />
          <form id="signup-form">
            <input name="email" type="text" />
            <input name="password" type="text" />
            <button type="submit">Sign Up<button>
          </form>
        </main>
        <script>
          const memberstack = window.$memberstackDom;
          const redirectTo = (path) => { window.location.href = path }
      		
          const signupMember => ({ email, password }) =>
          memberstack
          .signupMemberEmailPassword({ email, password })
          .then(({ data: member }) => { redirectTo("/onboarding") })
      
          const handleSubmit = (e) => {
            e.preventDefault();
            let email = e.target.email.value
            let password = e.target.password.value
            signupMember({ email, password })
           }
      	
           // listen for form submissions
           document.getElementById('signup-form')
           .addEventListener('submit', handleSubmit);
        </script>
      </body>
      

      Using our pre-built UI modals:

      <!-- memberstack.js script must be installed in <head /> -->
      <body>
        <main>
          <h1>Sign Up</h1>
          <br />
          <button id="signup">Sign Up</button>
        </main>
        <script>
          const memberstack = window.$memberstackDom;
          const signupButton = document.getElementById('signup');
      
          const redirectTo = (path) => { window.location.href = path }
      
          signupButton.addEventListener('click', () => {
            memberstack.openModal('SIGNUP').then(({ data }) => {
              memberstack.hideModal();
              redirectTo('/onboarding')
            });
          });
      		
        </script>
      </body>
      
    • Signup Example w/ @memberstack/dom

      You can utilize the same code shown in the raw JavaScript method section above. The only difference is that instead of using the memberstack.js script tag, you’d import the library at the top of your file.

      With modular apps, the best practice is typically creating a reusable memberstack instance that you can import in multiple files.

      // lib/memberstack.js
      
      import memberstackDOM from "@memberstack/dom";
      
      const memberstack = memberstackDOM.init({
        publicKey: "pk_...",
      });
      
      export default memberstack
      
      // auth.js
      
      import memberstack from "/lib/memberstack.js"
      
      const memberstack = window.$memberstackDom;
      const redirectTo = (path) => { window.location.href = path }
      
      // use snippet below if using a form
      const signupMember => ({ email, password }) =>
        memberstack
        .signupMemberEmailPassword({ email, password })
        .then(({ data: member }) => { redirectTo("/onboarding") })
      
      const handleSubmit = (e) => {
        e.preventDefault();
        let email = e.target.email.value
        let password = e.target.password.value
        signupMember({ email, password })
      }
      	
      // listen for form submissions
      document.getElementById('signup-form')
      .addEventListener('submit', handleSubmit);
      
      ////////////////////////////////////////////
      
      // use snippet below if using a modal
      const signupButton = document.getElementById('signup');
      
      signupButton.addEventListener('click', () => {
        memberstack.openModal('SIGNUP').then(({ data }) => {
          memberstack.hideModal();
          redirectTo('/onboarding')
        });
      });
      
      
      // signup.html 
      
      <body>
        <main>
          <h1>Sign Up</h1>
          <br />
          <form id="signup-form">
            <input name="email" type="text" />
            <input name="password" type="text" />
            <button type="submit">Sign Up<button>
          </form>
          <!-- or use a button below to trigger a modal instead -->
          <button id="signup">Sign Up</button>
        </main>
        <script type="module" src="./auth.js"></script>
      </body>
      

Logging a Member Out

await memberstack.logout()

Subscribing to Changes in Auth State

You can use the onAuthChange listener to track changes in the currently authenticated member, such as signup, login, and log out events.

memberstack.onAuthChange(member => {
  if (member) // Member is authenticated
  if (!member) // Member is not authenciated
})

The method returns an object that allows you to unsubscribe the current listener. After unsubscribing, Memberstack will no longer send auth updates to the callback function.

const listener = memberstack.onAuthChange(member => {...})

listener.unsubscribe()

Member Management

Getting The Current Member

The getCurrentMember method can be used to fetch the currently logged in member. If a persisted authenticated member is available in storage, Memberstack will return that object first. Otherwise we make an asynchronous API call to our severs to query the member.

let { data: member } = await memberstack.getCurrentMember()

// or 

memberstack.getCurrentMember().then(({ data: member }) => {
  if(member) {
    // do something with member data here
    // init 3rd party analytics, etc.
  }
})

See our DOM package reference for more details on the getCurrentMember method and the Member object.

Updating The Current Member

  • Update member custom fields

    updateMember allows you to update the custom fields on member.

    await memberstack.updateMember({
        customFields: {
          country: "Canada"
        }
    })
    
  • Update member email or password

    updateMemberAuth allows you to update a member's email or password.

    await memberstack.updateMemberAuth({
      email: "nicolas@gmail.com"
    })
    
    await memberstack.updateMemberAuth({
       oldPassword: "...",
       newPassword: "..."
    })
    

Examples

Basic

This example shows how to fetch an authenticated member, gate a protected page with an onAuthChange listener and write a welcome message to the DOM using member data.

Note: The example is written in ES6 module syntax w/ @memberstack/dom but you can easily add the memberstack.js static script instead and utilize the same logic.

<html lang="en">
  <body>
    <main>
      <h1>Dashboard</h1>
      <h2 id="welcome">Hello World</h2>
      <button id="logout">Logout</button>
    </main>
    <script type="module" src="./index.js"></script>
  </body>
</html>
// /lib/memberstack.js
import memberstackDOM from "@memberstack/dom";

export default memberstackDOM.init({
  publicKey: "pk_...",
});

// index.js

import memberstack from "./lib/memberstack.js"

const welcomeMessage = document.getElementById('welcome');
const logoutButton = document.getElementById('logout');

// use this logic for a re-usable Navbar
function handleMember(member) {
  if (member) {
    let name = member.customFields['name']
    welcomeMessage.innerHTML = `Welcome ${name}`
  } else {
    window.location.href="/login"
  }
}

memberstack.onAuthChange(handleMember);

memberstack.getCurrentMember().then(({ data: member }) => handleMember(member))

logoutButton.addEventListener('click', async () => {
  await memberstack.logout()
});

Was this article helpful?

Comments

0 comments

Please sign in to leave a comment.