Skip to main content
Memberstack Docs
Dashboard

Core Authentication

This guide covers all authentication methods available in the Memberstack DOM package. The examples use vanilla JavaScript and can be adapted to any framework.

/dom-package/core-authentication.md
Before You Start

Complete the Quick Start Guide and initialize Memberstack in your project with your public key before proceeding.

Email/Password Flow

The traditional email and password authentication method provides a familiar login experience. This example includes loading states and error handling for a better user experience.

// Add this HTML to your login page
<form id="loginForm">
  <input type="email" id="email" placeholder="Email" />
  <input type="password" id="password" placeholder="Password" />
  <button type="submit" id="loginButton">Log In</button>
  <div id="loginError" style="display: none; color: red;"></div>
</form>

// Add this JavaScript to handle the login
document.getElementById('loginForm').addEventListener('submit', async (event) => {
  event.preventDefault();
  const loginButton = document.getElementById('loginButton');
  const errorDiv = document.getElementById('loginError');

  // Disable button and show loading state
  loginButton.disabled = true;
  loginButton.textContent = 'Logging in...';
  errorDiv.style.display = 'none';

  // Get form values
  const email = document.getElementById('email').value;
  const password = document.getElementById('password').value;

  try {
    // Resolves { data: { member, tokens, redirect } }
    const { data } = await memberstack.loginMemberEmailPassword({
      email,
      password
    });

    // The SDK stores the session but never navigates: redirect yourself.
    // data.redirect is the member's login redirect from your dashboard
    // (Plans > Default settings > Redirects, or the member's plan); "/" by default.
    window.location.href = data.redirect || "/dashboard";
  } catch (error) {
    errorDiv.textContent = error.message || "Login failed. Please check your credentials.";
    errorDiv.style.display = 'block';
  } finally {
    // Reset button state
    loginButton.disabled = false;
    loginButton.textContent = 'Log In';
  }
});

loginMemberEmailPassword({ email, password }) resolves to { data: { member, tokens, redirect } } (tokens is { accessToken, expires, type }). The SDK saves the session token and the member, but it never changes the page: send the member to data.redirect (or wherever you like) yourself. data.redirect comes from the On Login redirect under Plans → Default settings → Redirects (a plan’s own redirect, when set, takes priority for members on that plan), and is "/" by default. Two things come before both: a login redirect set on the member, and, when your app requires email verification and the member isn’t verified, the On Verification Required redirect. See Redirects for the full order.

Best Practices
  • Always show loading states during authentication
  • Provide clear error messages for validation failures
  • Implement proper client-side email validation
  • Include password strength indicators

Passwordless Flow

Passwordless authentication provides a secure and user-friendly alternative to traditional passwords. Users receive a six-digit code by email (a code, not a login link), type it into your site, and you pass it to loginMemberPasswordless as passwordlessToken to log them in. You can configure the passwordless email template in the Memberstack dashboard under "Emails" > "Transactional" > "Passwordless Auth".

// Add this HTML to your login page
// Step 1: request the code by email
<form id="passwordlessForm">
  <input type="email" id="passwordlessEmail" placeholder="Email" />
  <button type="submit" id="passwordlessButton">Login with passwordless</button>
  <div id="passwordlessMessage"></div>
  <div id="passwordlessError" style="display: none; color: red;"></div>
</form>

// Step 2: enter the six-digit code from the email (hidden until step 1 succeeds)
<form id="verificationForm" style="display: none;">
  <input type="text" id="passwordlessCode" placeholder="Six-digit code" inputmode="numeric" />
  <button type="submit" id="verificationButton">Verify &amp; log in</button>
  <div id="verificationError" style="display: none; color: red;"></div>
</form>

// Add this JavaScript to handle passwordless login
let isEmailSent = false;
let pendingEmail = '';
const form = document.getElementById('passwordlessForm');
const button = document.getElementById('passwordlessButton');
const messageDiv = document.getElementById('passwordlessMessage');
const errorDiv = document.getElementById('passwordlessError');
const verificationForm = document.getElementById('verificationForm');
const verificationButton = document.getElementById('verificationButton');
const verificationError = document.getElementById('verificationError');

form.addEventListener('submit', async (event) => {
  event.preventDefault();

  if (isEmailSent) return; // Prevent multiple sends

  button.disabled = true;
  button.textContent = 'Sending...';
  errorDiv.style.display = 'none';

  const email = document.getElementById('passwordlessEmail').value;

  try {
    await memberstack.sendMemberLoginPasswordlessEmail({
      email
    });

    isEmailSent = true;
    pendingEmail = email; // Remember the email for the verification step
    messageDiv.textContent = 'Check your email for the login code';
    button.textContent = 'Check your email';

    // Reveal step 2 so the user can enter the code
    verificationForm.style.display = 'block';

    // Reset after 60 seconds
    setTimeout(() => {
      isEmailSent = false;
      button.disabled = false;
      button.textContent = 'Login with passwordless';
      messageDiv.textContent = '';
    }, 60000);
  } catch (error) {
    errorDiv.textContent = error.message || "Couldn't send login email. Please try again.";
    errorDiv.style.display = 'block';
    button.disabled = false;
    button.textContent = 'Login with passwordless';
  }
});

// Step 2: read the code from the form and verify it
verificationForm.addEventListener('submit', (event) => {
  event.preventDefault();
  const token = document.getElementById('passwordlessCode').value.trim();
  handlePasswordlessVerification(pendingEmail, token);
});

// Handle verification
async function handlePasswordlessVerification(email, token) {
  verificationButton.disabled = true;
  verificationButton.textContent = 'Verifying...';
  verificationError.style.display = 'none';

  try {
    // Resolves { data: { member, tokens, redirect } }, like loginMemberEmailPassword
    const { data } = await memberstack.loginMemberPasswordless({
      email: email,
      passwordlessToken: token
    });
    window.location.href = data.redirect || "/dashboard";
  } catch (error) {
    console.error("Verification failed:", error);
    verificationError.textContent = error.message || 'Invalid or expired code. Please try again.';
    verificationError.style.display = 'block';
    verificationButton.disabled = false;
    verificationButton.textContent = 'Verify & log in';
  }
}
Implementation Tips
  • Implement rate limiting for passwordless email requests
  • Show clear instructions after the code is sent
  • Handle code expiration gracefully
  • Provide a way to request a new code if needed
  • Consider adding a backup login method

Passwordless Signup

The same passwordless mechanism works for creating new accounts. Send a signup code with sendMemberSignupPasswordlessEmail, then complete signup with signupMemberPasswordless (passing the code as passwordlessToken). Just like email/password signup, you can attach customFields and free plans. On success the new member is signed in and persisted automatically.

// 1. Send the signup code to the member's email
await memberstack.sendMemberSignupPasswordlessEmail({
  email: "newuser@example.com"
});
// Resolves with { data: { success: true } } once the email is queued.

// 2. Complete signup with the code the member received by email
async function completePasswordlessSignup(email, code) {
  const { data } = await memberstack.signupMemberPasswordless({
    email,
    passwordlessToken: code,        // the code from the email
    // Optional, same as email/password signup:
    customFields: { "first-name": "Jane" },
    plans: [{ planId: "pln_free" }]
  });

  // The new member is signed in and persisted automatically.
  window.location.href = data.redirect || "/dashboard";
}

Social Provider Flow

Social authentication allows users to log in using their existing accounts from supported providers. This can significantly reduce friction in the signup and login process.

Provider Setup Required

Before implementing social login, configure your providers in the Memberstack dashboard:

  1. Navigate to your Memberstack dashboard
  2. Go to "Authentication" > "Auth providers"
  3. Enable and configure each provider you want to use
  4. Add authorized domains and callback URLs
// Add this HTML for social login buttons
<div class="social-login-buttons">
  <button onclick="loginWithProvider('google')" id="googleLogin">Login with Google</button>
  <button onclick="loginWithProvider('github')" id="githubLogin">Login with GitHub</button>
  <button onclick="loginWithProvider('facebook')" id="facebookLogin">Login with Facebook</button>
  <!-- Add more provider buttons as needed -->
</div>
<div id="socialLoginError" style="display: none; color: red;"></div>

// Add this JavaScript to handle social login
const PROVIDERS = {
  GOOGLE: "google",
  FACEBOOK: "facebook",
  GITHUB: "github",
  LINKEDIN: "linkedin",
  SPOTIFY: "spotify",
  DRIBBBLE: "dribbble"
};

async function loginWithProvider(provider) {
  const button = document.getElementById(provider + 'Login');
  const errorDiv = document.getElementById('socialLoginError');

  button.disabled = true;
  errorDiv.style.display = 'none';

  try {
    const { data } = await memberstack.loginWithProvider({
      provider,
      allowSignup: true  // If user doesn't exist, sign them up
    });
    // loginWithProvider opens a popup for the OAuth flow and RESOLVES once the
    // user finishes, this line runs after. The session is already stored for
    // you (onAuthChange has fired), so you can safely redirect now.
    window.location.href = data.redirect || "/dashboard";
  } catch (error) {
    errorDiv.textContent = `${provider} login failed: ${error.message}`;
    errorDiv.style.display = 'block';
  } finally {
    button.disabled = false;
  }
}

Supported Providers

  • Google
  • Facebook
  • GitHub
  • LinkedIn
  • Spotify
  • Dribbble

Implementation Tips

  • Use official provider logos
  • Handle connection failures gracefully
  • Implement proper scope handling
  • Consider data mapping strategies

Signing Up with a Provider

loginWithProvider (with allowSignup: true) handles both login and signup. To pre-set custom fields or free plans on a new account, use signupWithProvider. If the provider account is already connected to a member, that member is logged in instead and the custom fields and plans are ignored. If the email belongs to a member who has not connected this provider, the call rejects by default (for example with the message Please login with your email.). Like loginWithProvider, it opens a popup and resolves with { data: { member, tokens, redirect } } once the user finishes; the new member is signed in and persisted automatically.

// Sign up a new member with a social provider
async function signupWithGoogle() {
  try {
    const { data } = await memberstack.signupWithProvider({
      provider: "google",
      // Optional: prefill custom fields and assign free plans on signup
      customFields: { "sign-up-source": "google" },
      plans: [{ planId: "pln_free" }]
    });

    // Opens a popup. This runs AFTER the user finishes, the new member is
    // already signed in and persisted (onAuthChange has fired).
    console.log("Signed up:", data.member.auth.email);
    window.location.href = data.redirect || "/welcome";
  } catch (error) {
    // e.g. "Please login with your email." if that email already has a
    // password account. Popup errors are plain { message } objects; most
    // have no error.code.
    console.error("Provider signup failed:", error.message);
  }
}

Connecting & Disconnecting Providers

Let a logged-in member link additional providers to their account. connectProvider opens a popup; disconnectProvider is a direct request (no popup). Both resolve with { data: { providers } }, where providers is the member's full list of connected providers afterward, as objects: [{ provider: "google" }]. connectProvider also includes a success string at data.message; disconnectProvider does not.

// Connect an additional provider to the LOGGED-IN member (opens a popup)
async function connectGoogle() {
  const { data } = await memberstack.connectProvider({ provider: "google" });
  // data.providers is the member's full provider list after connecting
  console.log("Connected providers:", data.providers);
}

// Disconnect a provider (no popup, a direct request)
async function disconnectGoogle() {
  try {
    const { data } = await memberstack.disconnectProvider({ provider: "google" });
    console.log("Remaining providers:", data.providers);
  } catch (error) {
    // error.code is "account-set-password-before-disconnect" (their only
    // provider and they have no password) or "account-not-connected"
    console.error(error.message);
  }
}

A member cannot disconnect their only provider while they have no password: the call rejects with code account-set-password-before-disconnect. Have them setPassword() first (below).

Blocked or Closed Popups

The promise from loginWithProvider, signupWithProvider and connectProvider settles only when the popup sends back a result. If the browser blocks the popup, or the visitor closes it first, the promise stays pending: catch and finally do not run. To react, listen for the memberstack:popup event, which the SDK fires on window.

detail.statusFired when
blockedThe browser blocked the popup. Fired right away, still inside the click.
closedThe popup was closed without sending a result. Fired about 2 seconds after it closes. A popup that finishes sign-in, or reports an error, never fires it.

event.detail also carries action ("signup", "login" or "connect") and provider (for example "google"). The event is informational: if a blocked popup is later allowed and the visitor finishes, the original promise still resolves as usual.

// Needs @memberstack/dom 2.1.0 or later.
window.addEventListener("memberstack:popup", (event) => {
  const { status, action, provider } = event.detail;

  // The social-login example above disables its buttons until
  // the promise settles. A blocked or closed popup never settles
  // it, so re-enable them here.
  document
    .querySelectorAll(".social-login-buttons button")
    .forEach((button) => { button.disabled = false; });

  if (status === "blocked") {
    // Can happen in in-app browsers (Instagram, Facebook, ...).
    showMessage(
      `Your browser blocked the ${provider} window. ` +
      "Sign up with email instead."
    );
  }
  // "closed": the visitor closed the window. Usually nothing to show.
});
Avoid blocked popups
  • Call the method directly in the click handler. Browsers only allow a popup during the click, so an await before the call (fetching data, checking state) gets it blocked.
  • In-app browsers, such as Instagram and Facebook, often block popups or open them in place of your page. Offering email sign-up next to the provider button helps visitors coming from social ads.

Password Reset & Setting a Password

These methods power the "forgot password" flow programmatically (the pre-built modals do the same with no code). Reset is a two-step flow: request an email, then complete the reset with the 6-digit code from that email.

Forgot Password (reset flow)

// Step 1, send the reset email. For security this resolves the SAME whether
// or not the email exists, and the resolved `data` IS the message string.
async function requestPasswordReset(email) {
  const { data: message } = await memberstack.sendMemberResetPasswordEmail({ email });
  console.log(message);
  // "If this email exists, you'll receive an email with the reset instructions."
}

// Step 2, complete the reset with the 6-digit code from the email (pass it as `token`).
async function completePasswordReset(token, newPassword) {
  try {
    const { data } = await memberstack.resetMemberPassword({ token, newPassword });
    if (data.success) {
      // NOTE: this does NOT log the member in, send them to your login page.
      window.location.href = "/login";
    }
  } catch (error) {
    // "invalid-reset-code" if the code is wrong or expired
    console.error(error.message);
  }
}

Setting a Password (passwordless & social members)

Members who signed up with a provider or passwordless email have no password (auth.hasPassword === false). Use setPassword to add one so they can also log in with email + password. The member must be logged in, and no old password is required. It resolves with the updated member ({ data: member }).

// Add a password to a passwordless / social member (must be logged in).
async function addPassword(newPassword) {
  const { data: member } = await memberstack.setPassword({ password: newPassword });
  console.log("Password login enabled:", member.auth.hasPassword); // true
}
setPassword vs updateMemberAuth

Use setPassword to add a first password (no old password needed). To change an existing password, use updateMemberAuth({ oldPassword, newPassword }), see Password Management.

Logout & Session Management

In this section, you'll learn how to handle user sessions, implement a logout function, and manage session expiration.

Logout Function

Implementing a logout function is essential for user privacy and security. This example shows how to handle logout and clear the session:

// Handle logout
async function handleLogout() {
  try {
	// Resolves { data: { id, redirect } }. The SDK does not navigate.
	const { data } = await memberstack.logout();
	window.location.href = data?.redirect || "/login";
  } catch (error) {
	// The local session is only cleared after the request succeeds,
	// so on a network error the member is still logged in here.
	console.error("Logout failed:", error);
  }
}

logout() calls the API first and, only once that succeeds, removes the stored token (_ms-mid, from localStorage and the cookie) and the cached member, then fires onAuthChange(null). data.redirect is your On Logout redirect ("/" by default), or null when there was no session. Logging out does not invalidate the token itself: a copy of it still passes the Admin package’s verifyToken() and the REST verify-token endpoint until it expires.

Session Management

Proper session management is crucial for maintaining security and user experience. This guide will walk you through implementing robust session handling with Memberstack.

1. Basic Setup

First, configure Memberstack with session-specific options during initialization:

const memberstack = memberstackDOM.init({
  publicKey: "YOUR_PUBLIC_KEY",
  useCookies: true,                // Enable cookie persistence
  // setCookieOnRootDomain: true,  // Leave this out unless `domain` is an API host on your own root
  //                                  domain. With the default API host it turns cookie storage OFF
  //                                  (the token goes to localStorage instead).
});
Configuration Options

Memberstack supports both localStorage (default) and cookie-based storage for session management. Choose based on your specific needs:

  • useCookies (optional): Set to true to store the session token in a cookie (_ms-mid) instead of localStorage. On its own this sets a cookie for the current host only
  • setCookieOnRootDomain (optional): Only relevant when useCookies is true. The cookie is set on the root domain (shared across subdomains) only when the SDK's API host (the domain option) shares your site's root domain; with the default host client.memberstack.com the SDK falls back to localStorage
  • appId (optional): String app ID for multi-app / multi-tenant setups; sent as the X-APP-ID header on requests. Only needed if you have multiple Memberstack apps
  • domain (optional, advanced): Point the SDK at a custom API domain for enterprise or self-hosted deployments. The default host is client.memberstack.com; most users should leave this unset
The _ms-mid cookie and server-side code

The cookie exists only when you initialize with useCookies: true (with the hosted script: the data-memberstack-use-cookies attribute or memberstackConfig.useCookies). Without it the token is kept in localStorage["_ms-mid"] and your server never sees it.

The SDK writes the cookie from JavaScript as _ms-mid=<member JWT>; path=/; SameSite=Strict, plus Secure on https pages. It is not HttpOnly, and its expiry is set from the session length, rounded up to whole days, so it can outlive the token by up to a day. Memberstack’s servers never set it.

Because it is SameSite=Strict, the browser leaves it off a navigation that starts on another site. The first request after the return from Stripe Checkout (or a click from an email) reaches your server without _ms-mid, even though the member is logged in. Don’t make the checkout successUrl a page that redirects to login when the cookie is missing; check the session in the browser with getCurrentMember() on that page, or let it load and re-check on the next request.

2. Authentication State Management

Read the current member once on page load, then listen for authentication state changes to keep your UI up to date:

// Add this HTML for auth state display
<div id="authStateContainer">
  <div id="loadingState">Loading...</div>
  <div id="authenticatedState" style="display: none;">
    <p>Welcome, <span id="memberEmail"></span></p>
    <p>Session expires: <span id="sessionExpiry"></span></p>
    <button onclick="handleLogout()">Log Out</button>
  </div>
  <div id="unauthenticatedState" style="display: none;">
    Please log in
  </div>
</div>

// JavaScript for auth state management
document.addEventListener('DOMContentLoaded', () => {
  const loadingState = document.getElementById('loadingState');
  const authenticatedState = document.getElementById('authenticatedState');
  const unauthenticatedState = document.getElementById('unauthenticatedState');
  const memberEmailSpan = document.getElementById('memberEmail');
  const sessionExpirySpan = document.getElementById('sessionExpiry');

  function render(member) {
    loadingState.style.display = 'none';

    if (member) {
      authenticatedState.style.display = 'block';
      unauthenticatedState.style.display = 'none';
      memberEmailSpan.textContent = member.auth.email;

      // Display session information. On a fresh login the callback runs
      // just before the new token is stored, so read it on the next tick.
      setTimeout(() => {
        const token = memberstack.getMemberCookie();
        if (token) {
          const tokenData = parseJwt(token);
          const expiryDate = new Date(tokenData.exp * 1000);
          sessionExpirySpan.textContent = expiryDate.toLocaleString();
        }
      }, 0);
    } else {
      authenticatedState.style.display = 'none';
      unauthenticatedState.style.display = 'block';
    }
  }

  // Initial state: onAuthChange is NOT called when you subscribe,
  // so read the current member once on page load.
  memberstack.getCurrentMember()
    .then(({ data: member }) => render(member))
    .catch(() => render(null));

  // Later logins, signups and logouts on this page.
  // onAuthChange returns { unsubscribe }.
  const { unsubscribe } = memberstack.onAuthChange(render);
});

The onAuthChange callback receives the member object directly (or null), NOT a wrapper like { member, token }. This differs from auth methods like loginMemberEmailPassword(), which resolve to { data: { tokens, member, redirect } } — the member is nested at data.member, alongside the auth tokens and redirect.

The callback is not called with the current state when you subscribe, and it only fires in the tab where the login, signup or logout happened. Read the initial state with getCurrentMember().

3. Session Token Handling

Add these helper functions to work with session tokens:

// Parse JWT token to get expiration
function parseJwt(token) {
  try {
    const base64Url = token.split('.')[1];
    const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
    const jsonPayload = decodeURIComponent(atob(base64).split('').map(c =>
      '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)
    ).join(''));
    return JSON.parse(jsonPayload);
  } catch (error) {
    console.error('Error parsing token:', error);
    return {};
  }
}

4. Session Lifetime

Sessions cannot be extended from the browser. The token's lifetime is fixed when the member logs in (your app's session duration, 14 days by default), and getCurrentMember() only re-fetches member data: it does not issue a new token. When the token expires, the member has to log in again.

5. Session Expiration Handling

Add proactive session expiration checking to improve user experience:

// Check session expiration status
function checkSessionExpiration() {
  const token = memberstack.getMemberCookie();
  if (token) {
    const tokenData = parseJwt(token);
    const expiryTime = tokenData.exp * 1000;
    const timeUntilExpiry = expiryTime - Date.now();

    if (timeUntilExpiry < 300000) { // Less than 5 minutes
      alert("Your session is about to expire. Please log in again to stay signed in.");
    }
  }
}

// Check session status periodically
setInterval(checkSessionExpiration, 60000); // Check every minute

Common Issues & Solutions

  • Need other open tabs to notice a login or logout? The SDK does not sync tabs. Call getCurrentMember() when a tab regains focus
  • Sessions expiring too quickly? Session duration is an app setting applied at login
  • Working with subdomains? Review your domain configuration

Best Practices

  • Read the initial state with getCurrentMember(), then use onAuthChange for changes
  • Warn members before their session expires so they can log in again
  • Handle expired sessions gracefully
Need help?
Can't find what you're looking for? Our team is here to help.