Plain HTML & Script Tag
Add Memberstack to any site where you control the HTML (hand-written pages, a static host, or a site builder that allows custom code) with one script tag. You get signup, login and logout forms, member data on the page, gated content and paid Stripe Checkout, all from data-ms-* attributes, plus the full DOM package API in window.$memberstackDom.
- A Memberstack app. Your App ID is under Developer → Keys & IDs (see Find your App ID and keys).
- Serve your pages over
http://orhttps://(a local dev server is fine). Don’t open the HTML file from disk: checkout is rejected forfile://pages. - For paid plans, create a plan with a price in the dashboard. Prices have IDs starting with
prc_, plans withpln_. - Building with a bundler (React, Vue, Svelte…)? Use the npm package instead: DOM Package Quick Start. The
data-ms-*attributes on this page work only with the hosted script.
Install the Script Tag
Paste the script into the <head> of every page. This is the snippet the dashboard gives you, with your App ID in data-memberstack-app:
<head>
<!-- Memberstack: load it in <head>, without async or defer -->
<script
data-memberstack-app="app_your_app_id"
src="https://static.memberstack.com/scripts/v2/memberstack.js"
type="text/javascript"
></script>
</head>Load it synchronously in <head>, without async or defer. The script hides gated elements with CSS as soon as it runs, so loading it late lets gated content show before it is hidden.
- With the App ID snippet, the mode comes from the page’s hostname. A hostname registered in the dashboard as a Live domain runs in Live Mode, with real payments. One registered as a Test domain runs in Test Mode.
- A hostname that isn’t registered (for example
localhostor a staging host) runs in Test Mode. You can build and test there with the snippet as it is. - If you load the script with a public key instead (see Alternative: a public key), the key alone sets the mode and the domain doesn’t matter.
Find your App ID and keys
- In the dashboard sidebar, open Developer. The first tab is Keys & IDs.
- The Application ID card holds your App ID (
app_…). It is the same in Test Mode and Live Mode. - The API keys card holds your Public key and Secret key. Keys belong to one mode: switch the header toggle to Viewing: Test data to see the
pk_sb_/sk_sb_keys, or Viewing: Live data for the live ones.
Only the App ID or the public key (pk_…) goes in your HTML. The dashboard marks the secret key “Server-side only. Never expose this key in the browser.”
Already have a public key but not the App ID? Read it from the API: const { data: app } = await window.$memberstackDom.getApp(), then app.id is the App ID and app.mode is "sandbox" or "live".
Supported attributes
| Attribute | memberstackConfig key | What it does |
|---|---|---|
| data-memberstack-app="app_…" | appId | Your App ID, as in the dashboard snippet. Without a public key, the mode (Test or Live) comes from the page’s domain (see above). |
| data-memberstack-key="pk_…" | publicKey | Not in the dashboard snippet; a testing alternative to the App ID (see below). The key sets the mode: pk_sb_… is always Test Mode, any other key is Live Mode. When a key is sent, the App ID and the page’s domain are ignored. |
| data-memberstack-use-cookies | useCookies | Store the member token in a _ms-mid cookie instead of localStorage. See Token storage. |
| data-memberstack-set-cookie-on-root | setCookieOnRootDomain | Write that cookie on the root domain so subdomains share it. Needs use-cookies and a custom API domain on the same root. |
| data-memberstack-domain="https://…" | domain | A custom API domain (for example https://memberstack-client.example.com). Under Settings → Application → Set up custom domain, step 3 shows the script tag with this attribute when your app’s stack is Webflow, WordPress or Script tag. For other stacks it shows the npm snippet with the same URL in domain:, so copy that URL into this attribute. The other install snippets (Getting Started, Settings → Install code) leave it out, so add it yourself if you copied one of those. |
- The two cookie attributes switch on by being present. Any value turns them on, including
="false". To turn one off, remove the attribute. - The script reads these attributes with
document.querySelectoronce, at the moment it runs, so put them on the<script>tag itself. An element above the script also works; anything after it (for example in<body>) is not seen. When both an attribute and amemberstackConfigkey are set, the attribute wins. memberstackConfigis read once, when the Memberstack script runs. Setwindow.memberstackConfigin a script above the Memberstack script; setting it later has no effect.- You need at least one of: an App ID, a public key, or a page domain registered in the dashboard. With none of them the API answers
400 {"message":"Must pass an API key via x-api-key header"}.
Alternative: a public key (for testing)
The script also accepts your public key in place of the App ID, either as a data-memberstack-key attribute or as publicKey in window.memberstackConfig. No dashboard snippet uses it, and the App ID snippet above is the install to use for your site. Reach for a key only when you want to pin the mode while testing:
<head>
<!-- Alternative (testing): public key attribute instead of the App ID.
A pk_sb_ key always runs in Test Mode, on any domain. -->
<script
data-memberstack-key="pk_sb_your_public_key"
src="https://static.memberstack.com/scripts/v2/memberstack.js"
></script>
</head><head>
<!-- Alternative (testing): public key in window.memberstackConfig.
memberstackConfig must be set BEFORE the Memberstack script runs. -->
<script>
window.memberstackConfig = {
publicKey: "pk_sb_your_public_key",
useCookies: true
};
</script>
<script src="https://static.memberstack.com/scripts/v2/memberstack.js"></script>
</head>- When a key is sent, the key alone sets the mode, and the App ID and the page’s domain are ignored. A
pk_sb_…key always runs in Test Mode, on any domain: one you haven’t registered, and also one registered as a Live domain. Any other key always runs in Live Mode, with real payments. - On a domain you haven’t registered, the App ID snippet runs in Test Mode too, so you don’t need a key just for that.
Token storage
- Default: the member token is kept in
localStorage["_ms-mid"]and no cookie is written. - With
data-memberstack-use-cookies: the token goes in a_ms-midcookie withpath=/,SameSite=Strict,Secureon https pages, and an expiry set from the session length, rounded up to whole days (so it can outlive the token by up to a day). JavaScript writes it, so it is not HttpOnly. Use this when your own server needs to read the token from the cookie. - With
data-memberstack-set-cookie-on-root: the cookie getsdomain=<your root domain>only when the API domain shares that root (a custom API domain such ashttps://memberstack-client.example.comset withdata-memberstack-domain). With the default API host, the token silently stays in localStorage.
Use the API from Page JavaScript
The hosted script creates the same object you get from memberstackDOM.init() in the npm package and exposes it as window.$memberstackDom. When it is ready, the script sets window.$memberstackReady = true and dispatches a memberstack.ready event on document. Handle both, because the event has already fired if your code runs after the Memberstack script:
<script>
// Runs your callback once the Memberstack object exists.
// memberstack.ready fires once, as the hosted script finishes executing.
// If your code runs later, $memberstackReady is already true.
function onMemberstackReady(callback) {
if (window.$memberstackReady) {
callback(window.$memberstackDom);
} else {
document.addEventListener(
"memberstack.ready",
() => callback(window.$memberstackDom),
{ once: true }
);
}
}
onMemberstackReady(async (memberstack) => {
const { data: member } = await memberstack.getCurrentMember();
if (!member) {
console.log("Logged out");
return;
}
// Memberstack grants access for ACTIVE and TRIALING plan connections.
// Don't test pc.active: it is false for trialing members.
const hasPro = member.planConnections.some(
(pc) =>
pc.planId === "pln_your_plan_id" &&
(pc.status === "ACTIVE" || pc.status === "TRIALING")
);
console.log(member.auth.email, { hasPro });
});
</script>Every method on the other DOM Package pages works on window.$memberstackDom. One difference to remember: when you call loginMemberEmailPassword, signupMemberEmailPassword or logout, the method doesn’t navigate. It returns the server’s redirect and leaves navigation to you. Only the attribute-driven forms and buttons below redirect automatically.
Signup, Login and Logout
Mark a form with data-ms-form and its inputs with data-ms-member. The script handles submit, shows a loader and messages, and redirects when it’s done:
<!-- Signup: email + password, plus any custom fields -->
<form data-ms-form="signup">
<input data-ms-member="email" placeholder="Email" required />
<input data-ms-member="password" placeholder="Password" required />
<input data-ms-member="first-name" placeholder="First name" />
<button type="submit">Create account</button>
</form>
<!-- Login -->
<form data-ms-form="login">
<input data-ms-member="email" placeholder="Email" required />
<input data-ms-member="password" placeholder="Password" required />
<button type="submit">Log in</button>
</form>
<!-- Logout: any element works -->
<button data-ms-action="logout">Log out</button>- On a signup form, every
data-ms-memberinput other thanemailandpasswordis saved to the custom field with that key (herefirst-name). The field must already exist under Custom Fields in the dashboard with that exact key, and must not be admin-only. Any other key is silently dropped, with no error. - To give new members a free plan at signup, add
data-ms-plan:add="pln_your_plan_id"to the signup form (comma-separate several). Signup only assigns free plans; for paid plans use checkout. - Logout buttons can be any element with
data-ms-action="logout". After logout the visitor goes to your “On Logout” redirect, or, if that is the page they’re on, sees a message and the page reloads after 2 seconds.
Form types
| data-ms-form | Inputs (data-ms-member) | Notes |
|---|---|---|
| signup | email, password, any custom field key | Starts checkout after signup when a price is set (see Paid checkout). |
| login | email, password | |
| passwordless-signup | email, token, any custom field key | Two steps: the first submit emails a code, the second signs up with it. |
| passwordless-login | email, token | Two steps, like passwordless signup. |
| forgot-password | email | Sends the reset email. |
| reset-password | token, password | Sets the new password using the token from the reset email. |
| profile | custom field keys; optionally email, current-password, new-password | Logged-in members only. Saves custom fields, and changes email or password when those inputs are filled in. |
Passwordless forms need a wrapper with data-ms-passwordless="step-2" around the code input. The script hides it until the code has been sent, and an optional data-ms-passwordless-button value replaces the submit button’s label for step 2:
<form data-ms-form="passwordless-login">
<input data-ms-member="email" placeholder="Email" required />
<!-- Hidden until the code has been emailed -->
<div data-ms-passwordless="step-2">
<input data-ms-member="token" placeholder="6-digit code" />
</div>
<button type="submit" data-ms-passwordless-button="Log in">Email me a code</button>
</form>Prebuilt modals
If you don’t want to build forms, these attributes open Memberstack’s prebuilt modals on click:
<!-- Open Memberstack's prebuilt modals -->
<button data-ms-modal="signup">Sign up</button>
<button data-ms-modal="login">Log in</button>
<button data-ms-modal="forgot-password">Forgot password?</button>
<button data-ms-modal="profile">My account</button>Show Member Data
Outside a form, data-ms-member fills the element with the logged-in member’s data: email, id, or any custom field key. On an <img> it sets the src:
<p>Signed in as <span data-ms-member="email"></span></p>
<p>Hello, <span data-ms-member="first-name"></span></p>
<p>Member since <span data-ms-member="signup-date"></span></p>
<p>Member since <span data-ms-member="signup-date.toLocaleDateString"></span></p>
<img data-ms-member="profile-image" alt="" />
<!-- Sends a logged-in member to their login redirect -->
<a href="#" data-ms-action="login-redirect">Go to my dashboard</a>signup-dateshows the signup date asDate.toDateString(). Add aDatemethod name after a dot, such assignup-date.toLocaleDateString, to format it with that method.- Inside a
data-ms-form="profile"form, the same attribute pre-fills the inputs.
Redirects After Signup, Login and Logout
The server decides where a member goes after signup, login and logout. For a new app (unless you created it from a template), every redirect is / (the dashboard shows it as “Homepage”). Change them in the dashboard:
- App defaults: Plans → Default settings (“For members without a plan”) → Redirects. The rows are On Signup / On Purchase, On Login, On Logout and On Verification Required. Shortcut: Authentication → Overview → Login redirects.
- Per plan: Plans → select a plan → Redirects (“Override default redirects for members with this plan.”). Free plans label the first row On Signup.
For a given member, the server picks the first match:
- Login only: the member’s own login redirect, if one is set on the member.
- Login or signup: if the app requires email verification and the member isn’t verified, the On Verification Required redirect.
- Plan redirect: among the member’s plans that aren’t canceled, plan redirects that are set and aren’t
/, by plan priority. A plan redirect left at/is skipped. - App default from Default settings.
Paths get a leading /; full https:// URLs are used as they are.
Override the redirect on a page
<!-- 1. The form's own redirect attribute beats data-ms-redirect and the server redirect -->
<form data-ms-form="login" redirect="/members">
<input data-ms-member="email" required />
<input data-ms-member="password" required />
<button type="submit">Log in</button>
</form>
<!-- 2. data-ms-redirect: stored when the element is clicked.
"current-url" means "come back to this page" (path only). -->
<button data-ms-modal="login" data-ms-redirect="current-url">Log in to keep reading</button>After a login or signup form (or a login, signup or forgot-password modal), the script applies the first rule that matches:
- If the page is
/and the server redirect is/, the page reloads. Nothing below is checked. - The form’s
redirectattribute, used as written. - The last clicked
data-ms-redirectvalue (kept insessionStorageand removed once used).current-urlis the current path, without query string or hash. - The server redirect, if it differs from the current path. If it is the current path, the form shows its success message and the page reloads after 2 seconds.
data-ms-redirect doesn’t navigate by itself. Put it on the element that opens the modal, or on something the visitor clicks before submitting the form. It is not used for logout or for the page after checkout.
Gate Content on the Page
Add data-ms-content to any element. Visitors who don’t match have the element removed from the page:
<!-- Only logged-in members see this -->
<div data-ms-content="members">Welcome back!</div>
<!-- Only logged-out visitors see this -->
<div data-ms-content="!members">
<button data-ms-modal="signup">Sign up</button>
</div>
<!-- Only members with access to the "premium" content group -->
<div data-ms-content="premium">Premium article…</div>
<!-- Everyone WITHOUT access to "premium" -->
<div data-ms-content="!premium">Upgrade to read the full article.</div>| data-ms-content | Shown to |
|---|---|
| members | Logged-in members. |
| !members | Logged-out visitors. |
| <content ID> | Members with access to that content group. Use the group’s Content ID from Gated Content in the dashboard. |
| !<content ID> | Everyone without access to that group. |
| paid-plans | Members with a paid plan that isn’t canceled (a member with a failed payment still counts). |
| is-trialing | Members with a plan in a trial. |
| has-failed-payment | Members with a plan whose status is REQUIRES_PAYMENT or REQUIRES_AUTHENTICATION. |
A value the script doesn’t recognize (not one of your Content IDs, and not a built-in value such as those above, free-plans, no-plans, verified or has-password, or their ! forms) is ignored, so the element shows to everyone. If gated content shows to logged-out visitors, check the Content ID for typos; the match is exact and case-sensitive. (The one exception: on a first visit when the script can’t reach Memberstack, it hides every data-ms-content element without a !.)
A member has access to a content group when one of the group’s plans is on their account with status ACTIVE or TRIALING, or the group allows all members. If your app requires email verification, unverified members have no access. REQUIRES_PAYMENT, REQUIRES_AUTHENTICATION and CANCELED don’t grant access. The server computes this; the script reads it.
To protect whole pages, add Restricted URLs to the content group (filters “Equals” and “Starts with”) and set its 🚫 Access denied URL. Visitors without access are sent there with window.location.replace(). This redirect runs in the browser, after the page’s HTML has already been delivered.
Avoid the flash of gated content
The script hides gated elements in two passes. As soon as it runs, it adds CSS built from cached data (the last member and content groups it saw). Then, once the page is parsed, it removes every element the visitor shouldn’t see. If it has cached data it uses that right away; only when there is no cache (or after checkout) does it wait for a fresh fetch. The fresh data is saved for the next page load, so a change made elsewhere (for example a plan added from your server) shows up on the following page. Gated content can show briefly in these cases:
- on a visitor’s first page load;
- on the first page load after a logout, or after a login, signup or plan change made from your own JavaScript (those clear the cache; the hosted forms and modals refill it);
- right after checkout: the old cached data is used until the member is fetched again, so content for the member’s previous state (such as an upgrade prompt) can show briefly;
- when the script loads late (
async,defer, or at the end of<body>).
Hide the element yourself in the markup, and let the script reveal it with data-ms-bind:style:
<div
data-ms-content="premium"
style="display:none"
data-ms-bind:style="display:block"
>
Premium content
</div>- Visitors without access never see it: it starts hidden and the script removes it.
- For visitors with access, the script sets
display:blockafter its removal pass. Useflex,gridor another value if your layout needs it. On a first load (no cache) that happens a moment after the page paints, once the script has fetched your content groups; reserve the space (for example withmin-height) if the jump bothers you. data-ms-bind:styletakes oneproperty:valuepair, with no space before the colon. Anything more (a second pair, a;) silently leaves the element hidden for everyone.- Keep the script synchronous in
<head>so the cached CSS is in place before the first paint.
Paid Checkout
Put data-ms-price:add with a price ID on a button or link:
<!-- Logged out: stores the price and follows the link to your signup page.
Logged in: starts Stripe Checkout straight away. -->
<a href="/signup" data-ms-price:add="prc_your_price_id">Get Pro</a>
<!-- Or open the prebuilt signup modal; checkout starts after signup.
Show this one to logged-out visitors only: for a logged-in member the
click would open the signup modal as well as starting checkout. -->
<div data-ms-content="!members">
<button data-ms-modal="signup" data-ms-price:add="prc_your_price_id">Get Pro</button>
</div>- Logged in: the click opens Stripe Checkout for that price.
- Logged out: the click stores the price for this tab and lets the click continue (follows the link, opens the modal). When the visitor then signs up with a signup form, the signup modal, or a social signup button, checkout starts right after the account is created.
- A plain login doesn’t start checkout. A returning member who logs in after clicking a price button follows their login redirect. Show them the price button again once they’re logged in, or use the button below.
You can also set the price on the signup form itself, which is useful for a dedicated signup page:
<!-- signup.html: checkout starts right after the account is created -->
<form data-ms-form="signup" data-ms-price:add="prc_your_price_id">
<input data-ms-member="email" required />
<input data-ms-member="password" required />
<button type="submit">Create account and pay</button>
</form>Related attributes
| Attribute | What it does |
|---|---|
| data-ms-price:update="prc_a,prc_b" | For plan switching; the first price is the checkout price. Logged out: stores the first price, like price:add. Logged in without a subscription: checkout with the first price. Logged in with an active subscription: opens the Stripe Customer Portal with these prices to switch between. |
| data-ms-price:remove="all" | Clears the stored price on click (or, on a signup form, right after the account is created, so checkout doesn’t start). |
| data-ms-coupon="…" | On a price button or signup form: passes that coupon ID (a Stripe coupon or promo_… promotion code ID) to the checkout. |
| data-ms-action="return-to-checkout" | Starts checkout again for the stored price. Shown only to logged-in members who have a stored price. |
| data-ms-action="customer-portal" | Opens the Stripe Customer Portal. Shown only to logged-in members who have a Stripe customer. |
Where members land after payment
Attribute checkout doesn’t set a success URL, and no attribute sets one. After payment, Memberstack sends the member to:
- if your app requires email verification and the member isn’t verified yet, the On Verification Required redirect;
- otherwise, their On Signup / On Purchase redirect (plan redirect first, then the app default; the new plan counts), joined to your site’s origin. With an untouched app that is
/, your homepage; - otherwise, the page that started checkout, without its query string.
Memberstack adds ?forceRefetch=true&fromCheckout=true&msPriceId=prc_…&stripePriceId=price_… to that URL. The hosted script reads forceRefetch to fetch the member fresh before gating and redirecting, so the new plan applies on the landing page. If the visitor cancels, Stripe sends them back to the page that started checkout, without its query string.
Start checkout from JavaScript
Call purchasePlansWithCheckout when you want to choose the success page yourself:
<button id="buy">Get Pro</button>
<script>
document.getElementById("buy").addEventListener("click", async () => {
const memberstack = window.$memberstackDom;
const { data: member } = await memberstack.getCurrentMember();
if (!member) {
// Checkout needs a logged-in member (otherwise the API answers 401)
memberstack.openModal("SIGNUP");
return;
}
try {
// Redirects to Stripe Checkout when the promise resolves
await memberstack.purchasePlansWithCheckout({
priceId: "prc_your_price_id",
successUrl: "/welcome", // becomes https://your-site.com/welcome
cancelUrl: "/pricing"
});
} catch (err) {
// A 429 rejects with a plain string, not an object
const message = typeof err === "string" ? err : err?.message ?? "Checkout failed";
const code = typeof err === "object" ? err?.code : undefined; // undefined for 429
alert(message);
}
});
</script>- The member must be logged in; otherwise the API answers 401.
successUrlandcancelUrlcan be relative. The SDK turns/welcome,?xor#xintolocation.origin+ value,welcomeintoorigin + "/welcome", and passeshttps://…through.- The query string of
successUrlis dropped./welcome?plan=prolands on/welcome?forceRefetch=true&fromCheckout=true&…. A#hashsurvives only when the URL has no?. Read the price frommsPriceIdinstead of passing your own parameters. - Without
successUrl, the member lands where attribute checkout sends them (above). WithoutcancelUrl, cancel returns to the current page. - By default the method redirects to Stripe itself. Pass
autoRedirect: falseto get{ data: { url } }back and redirect yourself. - The test-card modal doesn’t open on this path, even in Test Mode.
- Every URL sent must be
http(s). From a page opened from disk the API answers 400 with “… must be a valid http(s) URL. Checkout cannot redirect back to a page opened from disk — serve your page over http(s) and try again.”
Checkout rate limit
Creating a checkout session is limited to 1 request per 5 seconds per IP address. Every attempt counts, including ones rejected as not logged in. Over the limit, the API answers 429 with a Retry-After header and a text (not JSON) body, Too many requests, please try again later.
- From JavaScript, the promise rejects with that string, so
err.messageanderr.codeareundefined. Handle both shapes as in the example above. - On an attribute button, the loader disappears and no error message is shown. The script ignores further clicks while a checkout request is in progress, but a second checkout started within 5 seconds (for example by an automated test, or from two buttons) is rejected. In Test Mode the checkout session is created when the button is clicked, before the test-card modal opens, so closing the modal and clicking again within 5 seconds also hits the limit and silently does nothing. Wait 5 seconds and click again.
The test-card modal in Test Mode
In Test Mode, checkout started from an attribute (a price button, a signup form with a price, the signup modal, return-to-checkout) opens a “Copy Stripe Test Card” modal before Stripe. It offers 4242 4242 4242 4242 by default, and more cards in its dropdown: Visa Debit (4000 0566 5566 5556), Mastercard (5555 5555 5555 4444), American Express, and two decline cards (generic decline and insufficient funds).
- Continue to Test Checkout goes on to Stripe. Closing the modal abandons the checkout, with no redirect.
- It can’t be turned off: there is no attribute, config key or global for it. It doesn’t appear in Live Mode, or when you call
purchasePlansWithCheckoutyourself. - Also in Test Mode, the script shows a small Test Mode badge at the bottom of every page; click it to open the inspector.
Complete Example
One page with signup, login, logout, member data, a paid upgrade and flash-free gated content. Replace the placeholder IDs, create a content group with the Content ID premium, and serve it over http(s):
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>My membership site</title>
<script
data-memberstack-app="app_your_app_id"
src="https://static.memberstack.com/scripts/v2/memberstack.js"
type="text/javascript"
></script>
</head>
<body>
<!-- Logged-out visitors -->
<section data-ms-content="!members">
<form data-ms-form="signup">
<input data-ms-member="email" placeholder="Email" required />
<input data-ms-member="password" placeholder="Password" required />
<button type="submit">Sign up</button>
</form>
<form data-ms-form="login">
<input data-ms-member="email" placeholder="Email" required />
<input data-ms-member="password" placeholder="Password" required />
<button type="submit">Log in</button>
</form>
</section>
<!-- Logged-in members -->
<section data-ms-content="members">
<p>Signed in as <span data-ms-member="email"></span></p>
<button data-ms-action="logout">Log out</button>
<!-- Paid upgrade (in Test Mode the test-card modal opens first) -->
<button data-ms-price:add="prc_your_price_id">Upgrade to Pro</button>
</section>
<!-- Members with access to the "premium" content group, no flash -->
<section
data-ms-content="premium"
style="display:none"
data-ms-bind:style="display:block"
>
<h2>Premium</h2>
<p>Only members with access see this.</p>
</section>
</body>
</html>Protecting Content for Real
Gated elements are in your HTML. The script removes them in the browser, and Restricted URLs redirect in the browser, but your host still serves the full page to anyone who requests it (or turns off JavaScript). Use attribute gating for layout and upsells, not for content that must stay private.
For content that must stay private, choose one of these:
- Hosted content. Add the content to the group’s Hosted content section in the dashboard and load it with
getSecureContent({ contentId }). Memberstack checks access on the server before returning it. See Protected Content. - Your own server check. Send the member token to your server and verify it there before returning anything.
getMemberCookie()returns the raw token (orundefined). Withdata-memberstack-use-cookiesthe browser also sends the_ms-midcookie with requests to the same host.
<div id="premium"></div>
<script>
async function loadPremium() {
const memberstack = window.$memberstackDom;
const token = memberstack.getMemberCookie(); // raw member JWT, or undefined
if (!token) return;
const res = await fetch("/api/premium", {
headers: { Authorization: `Bearer ${token}` }
});
if (res.ok) {
document.getElementById("premium").innerHTML = await res.text();
}
}
// Run once Memberstack is ready (the event may already have fired)
if (window.$memberstackReady) {
loadPremium();
} else {
document.addEventListener("memberstack.ready", loadPremium, { once: true });
}
</script>Verify the token on the server with the Admin Node package or the Admin REST API, always checking that the token was issued for your App ID.