### Memberstack Server-Side Admin Package Setup (Bash)
Source: https://memberstack.com/llms-full.txt
Instructions for installing and setting up the Memberstack server-side admin package using npm or yarn. It includes initializing the package with a secret key, which is essential for server-side operations and should never be exposed in client-side code.
```bash
npm install @memberstack/admin
# or
yarn add @memberstack/admin
```
--------------------------------
### Memberstack MCP Installation
Source: https://memberstack.com/llms-full.txt
Instructions for installing the Memberstack MCP server across different AI environments.
```APIDOC
## Installation
### Claude Code
`claude mcp add memberstack --scope user npx mcp-remote https://mcp.memberstack.com/mcp`
### Codex
`codex mcp add memberstack -- npx mcp-remote https://mcp.memberstack.com/mcp`
### Cursor / Claude Desktop (JSON config)
```json
{
"mcpServers": {
"memberstack": {
"command": "npx",
"args": ["mcp-remote", "https://mcp.memberstack.com/mcp"]
}
}
}
```
```
--------------------------------
### Role-Based Access Control (RBAC) Example
Source: https://memberstack.com/llms-full.txt
Example implementation for checking member roles and plan access.
```APIDOC
## Role-Based Access Control
### Description
Provides middleware functions to enforce role-based access control, such as checking if a member has a specific plan.
### Method
N/A (Middleware functions)
### Endpoint
N/A
### Middleware Function: `requirePlan`
#### Description
Checks if the authenticated member has a specific active plan.
#### Parameters
- **requiredPlanId** (string) - Required - The ID of the plan that the member must have.
#### Usage Example
```javascript
// Check if member has specific plan
function requirePlan(requiredPlanId) {
return async (req, res, next) => {
if (!req.member?.id) {
return res.status(401).json({ error: 'Auth required' });
}
const { data: member } = await memberstack.members.retrieve({
id: req.member.id
});
const hasPlan = member.planConnections.some(
plan => plan.planId === requiredPlanId && plan.status === 'ACTIVE'
);
if (!hasPlan) {
return res.status(403).json({ error: 'Plan required' });
}
next();
};
}
// Example usage with authMiddleware (assumed to be defined elsewhere)
app.get('/premium', authMiddleware, requirePlan('pln_premium'), (req, res) => {
res.json({ content: 'Premium only content' });
});
```
```
--------------------------------
### Memberstack Modal Flow Pattern Example
Source: https://memberstack.com/llms-full.txt
Illustrates a common pattern for handling user authentication flows using Memberstack modals. This example shows how to open a login modal, wait for it to resolve upon successful login, manually close the modal, and then redirect the user to a dashboard.
```javascript
async function handleLogin() {
try {
// Open login modal - resolves when login succeeds
const result = await memberstack.openModal("LOGIN");
console.log("Login successful:", result);
// CRITICAL: Close modal manually
await memberstack.hideModal();
// Redirect or update UI
window.location.href = '/dashboard';
} catch (error) {
console.error("Login failed:", error.message);
}
}
```
--------------------------------
### SvelteKit App Initialization
Source: https://developers.memberstack.com/mcp-server
This snippet shows the initialization process for a SvelteKit application, including loading necessary modules and starting the application with specific node IDs and data.
```javascript
{
const __sveltekit_fklneg = {
base: new URL(".", location).pathname.slice(
0,
-1
)
};
const element = document.currentScript.parentElement;
Promise.all([
import("./_app/immutable/entry/start.mYk8LYQ8.js"),
import("./_app/immutable/entry/app.D6X76-F7.js")
]).then(([
kit,
app
]) => {
kit.start(app, element, {
node_ids: [0, 26],
data: [null, null],
form: null,
error: null
});
});
}
```
--------------------------------
### Svelte/SvelteKit Integration
Source: https://memberstack.com/llms-full.txt
This snippet shows how to initialize Memberstack and manage member state using Svelte stores. It includes usage examples for layout and components.
```APIDOC
## Svelte/SvelteKit Integration
### Description
This section provides a Svelte store (`memberstack.js`) to manage Memberstack initialization, authentication state, and member data. It demonstrates how to use this store within your SvelteKit application's layout and components.
### Initialization and Store Setup (`stores/memberstack.js`)
```javascript
// stores/memberstack.js
import { writable } from 'svelte/store';
import memberstackDOM from '@memberstack/dom';
import { browser } from '$app/environment';
export const member = writable(null);
export const loading = writable(true);
let memberstackInstance = null;
let authListener = null;
export function initMemberstack() {
if (!browser) return null;
if (!memberstackInstance) {
memberstackInstance = memberstackDOM.init({
publicKey: import.meta.env.VITE_MEMBERSTACK_KEY,
useCookies: true
});
authListener = memberstackInstance.onAuthChange((m) => {
member.set(m);
loading.set(false);
});
memberstackInstance.getCurrentMember().then(({ data }) => {
member.set(data);
loading.set(false);
});
}
return memberstackInstance;
}
export function getMemberstack() {
return memberstackInstance;
}
```
### Usage in `+layout.svelte`
```svelte
Loading...
{:else if $member}Welcome, {$member.auth.email}
{:else} {/if} ``` ``` -------------------------------- ### Implementing Cursor-Based Pagination (JavaScript) Source: https://developers.memberstack.com/admin-rest-api/data-tables Shows how to implement cursor-based pagination to retrieve data in pages. This example fetches the first page and then uses the `endCursor` from the response to fetch the subsequent page. It requires axios and a BASE_URL. ```javascript // First page const firstPage = await axios.post(`${BASE_URL}/products/records/query`, { query: { findMany: { take: 20, orderBy: { createdAt: 'desc' } } } }, { headers }); // Next page using cursor const nextPage = await axios.post(`${BASE_URL}/products/records/query`, { query: { findMany: { take: 20, after: firstPage.data.data.pagination.endCursor, orderBy: { createdAt: 'desc' } } } }, { headers }); ``` -------------------------------- ### Install @memberstack/dom Package Source: https://memberstack.com/llms-full.txt Installs the Memberstack DOM package using npm, yarn, or pnpm. This is the only supported client-side package for new projects. ```bash npm install @memberstack/dom # OR yarn add @memberstack/dom # OR pnpm add @memberstack/dom ``` -------------------------------- ### Memberstack MCP Server Configuration Source: https://developers.memberstack.com/mcp-server Instructions for installing and registering the Memberstack MCP server with compatible AI clients. ```APIDOC ## MCP Server Installation ### Description Register the Memberstack MCP server with your AI client to enable direct interaction with your Memberstack projects. ### Installation Command ```bash claude mcp add memberstack --scope user npx mcp-remote https://mcp.memberstack.com/mcp ``` ### Authentication - **Method**: OAuth 2.1 with PKCE - **Process**: Upon first use, the client triggers a browser-based authentication flow. Credentials are never shared with the AI client. ### Verification - **Tool**: `listApps` - **Usage**: Ask the AI assistant: "List my Memberstack apps" to confirm connectivity. ``` -------------------------------- ### Install Memberstack MCP Server Source: https://memberstack.com/llms-full.txt Commands and configurations to add the Memberstack MCP server to Claude Code, Codex, or Claude Desktop. ```bash claude mcp add memberstack --scope user npx mcp-remote https://mcp.memberstack.com/mcp ``` ```bash codex mcp add memberstack -- npx mcp-remote https://mcp.memberstack.com/mcp ``` ```json { "mcpServers": { "memberstack": { "command": "npx", "args": ["mcp-remote", "https://mcp.memberstack.com/mcp"] } } } ``` -------------------------------- ### Member JSON Patterns Source: https://memberstack.com/llms-full.txt Examples of how to update and retrieve member JSON data, including nested objects, arrays, user preferences, and onboarding progress. ```APIDOC ## Member JSON Patterns ### Description This section provides code examples for common operations involving the Member JSON object, such as updating nested preferences, managing favorite items in an array, retrieving user preferences with default values, and tracking onboarding progress. ### Update Nested Preference Updates a specific key within the nested `preferences` object of the member's JSON. ```javascript async function updateNestedPreference(key, value) { const { data } = await memberstack.getMemberJSON(); const currentJson = data || {}; await memberstack.updateMemberJSON({ json: { ...currentJson, preferences: { ...currentJson.preferences, [key]: value } } }); } ``` ### Add Item to Favorites Array Adds a new item to the `favorites` array in the member's JSON, ensuring no duplicates. ```javascript async function addToFavorites(itemId) { const { data } = await memberstack.getMemberJSON(); const currentJson = data || {}; const favorites = currentJson.favorites || []; if (!favorites.includes(itemId)) { await memberstack.updateMemberJSON({ json: { ...currentJson, favorites: [...favorites, itemId] } }); } } ``` ### Get User Preferences with Defaults Retrieves user preferences from the member's JSON, applying default values if specific preferences are not set. ```javascript async function getUserPreferences() { const { data } = await memberstack.getMemberJSON(); const json = data || {}; return { theme: json.preferences?.theme || 'light', language: json.preferences?.language || 'en', notifications: json.preferences?.notifications ?? true, timezone: json.preferences?.timezone || 'UTC' }; } ``` ### Complete Onboarding Step Records a completed onboarding step, updates the last step, and sets the update timestamp. ```javascript async function completeOnboardingStep(step) { const { data } = await memberstack.getMemberJSON(); const currentJson = data || {}; const completedSteps = currentJson.onboarding?.completedSteps || []; await memberstack.updateMemberJSON({ json: { ...currentJson, onboarding: { ...currentJson.onboarding, completedSteps: [...new Set([...completedSteps, step])], lastStep: step, updatedAt: new Date().toISOString() } } }); } ``` ``` -------------------------------- ### JavaScript Error Handling Example Source: https://developers.memberstack.com/admin-rest-api/data-tables Demonstrates how to handle API errors in JavaScript using axios. It includes checks for server response errors, specific status codes (400, 404), and network errors. ```javascript try { const response = await axios.post(`${BASE_URL}/products/records`, { data: { name: "New Product", price: 29.99 } }, { headers }); console.log('Record created:', response.data); } catch (error) { if (error.response) { // Server responded with error console.error('Error code:', error.response.data.code); console.error('Error message:', error.response.data.message); console.error('Status:', error.response.status); switch (error.response.status) { case 400: // Handle validation errors break; case 404: // Handle not found errors break; default: // Handle other errors } } else { // Network or other error console.error('Network error:', error.message); } } ``` -------------------------------- ### Update Data Record using Axios Source: https://developers.memberstack.com/admin-rest-api/data-tables Provides an example of updating a Memberstack data table record using the Axios JavaScript library. It demonstrates setting up the API key, base URL, headers, and making the PUT request with the updated data. ```javascript const axios = require('axios'); const API_KEY = process.env.MEMBERSTACK_SECRET_KEY; const BASE_URL = 'https://admin.memberstack.com/v2/data-tables'; const headers = { "X-API-KEY": API_KEY, "Content-Type": "application/json" }; const response = await axios.put( `${BASE_URL}/products/records/cm8abc123yza234ghi`, { data: { price: 39.99, inStock: false } }, { headers } ); console.log(response.data); ``` -------------------------------- ### Memberstack Button Actions with HTML Source: https://memberstack.com/llms-full.txt Provides examples of HTML buttons that trigger various Memberstack actions, including logging out, opening specific modals (login, signup, profile, forgot password), and managing Stripe-related actions like adding or updating prices and accessing the customer portal. ```html ``` -------------------------------- ### Launch Stripe Customer Portal via Memberstack SDK Source: https://memberstack.com/llms-full.txt Demonstrates how to initiate a Stripe Customer Portal session. It supports optional parameters like return URLs and configuration, and handles both automatic redirection and manual URL retrieval. ```javascript try { await memberstack.launchStripeCustomerPortal({ returnUrl: "/account" }); } catch (error) { console.error("Portal launch failed:", error.message); } try { const { data } = await memberstack.launchStripeCustomerPortal({ returnUrl: "/account", autoRedirect: false }); window.open(data.url, '_blank'); } catch (error) { console.error("Portal launch failed:", error.message); } ``` -------------------------------- ### Initialize SvelteKit Application Source: https://developers.memberstack.com/admin-node-package A script to initialize the SvelteKit application environment, setting the base URL and loading the necessary entry modules. ```javascript { __sveltekit_fklneg = { base: new URL(".", location).pathname.slice(0, -1) }; const element = document.currentScript.parentElement; Promise.all([ import("./_app/immutable/entry/start.mYk8LYQ8.js"), import("./_app/immutable/entry/app.D6X76-F7.js") ]).then(([kit, app]) => { kit.start(app, element, { node_ids: [0, 3], data: [null,null], form: null, error: null }); }); } ``` -------------------------------- ### Initialize Memberstack Admin Package (Node.js) Source: https://developers.memberstack.com/llms.txt Shows how to initialize the `@memberstack/admin` package for server-side operations. It requires a secret API key and provides an interface for managing members, plans, and verifying tokens. Remember to never expose secret keys in client-side code. ```javascript import memberstackAdmin from '@memberstack/admin'; const memberstack = memberstackAdmin.init('sk_your_secret_key'); // Secret key, NOT public key ``` -------------------------------- ### Get Auth Token API Source: https://memberstack.com/llms-full.txt Retrieves the authentication token for the current member. ```APIDOC ## Get Auth Token ### Description Retrieves the authentication token (cookie) for the currently logged-in member. This token can be used for authenticated requests to your backend. ### Method - **Method**: GET (Conceptual - Function call) - **Endpoint**: N/A (Function call: `memberstack.getMemberCookie()`) - **Description**: Synchronously retrieves the member's authentication token. - **Returns**: `string | null` - The authentication token if the user is logged in, otherwise null. ### Usage Example ```javascript const token = memberstack.getMemberCookie(); if (token) { console.log("Auth token:", token); // Use for authenticated API requests to your backend fetch('/api/protected-resource', { headers: { 'Authorization': `Bearer ${token}` } }); } else { console.log("No auth token - user not logged in"); } ``` ``` -------------------------------- ### Memberstack SDK Method vs Modal Parameters Source: https://memberstack.com/llms-full.txt Demonstrates the difference in parameter structures when using SDK methods versus opening modals. ```javascript memberstack.signupMemberEmailPassword({ plans: [{ planId: "pln_..." }] }); memberstack.openModal("SIGNUP", { signup: { plans: ["pln_..."] } }); ``` -------------------------------- ### POST /signupWithProvider Source: https://memberstack.com/llms-full.txt Initiates a signup process using a social identity provider. ```APIDOC ## POST signupWithProvider ### Description Redirects the user to the specified social provider for signup. Note: This method causes an immediate browser redirect. ### Method POST ### Endpoint memberstack.signupWithProvider(params) ### Parameters #### Request Body - **provider** (string) - Required - One of: google, facebook, github, linkedin, dribbble, spotify - **allowLogin** (boolean) - Optional - Allow existing users to login instead ### Request Example { "provider": "google", "allowLogin": true } ``` -------------------------------- ### GET /getCurrentMember Source: https://memberstack.com/llms-full.txt Retrieves the currently authenticated member's profile information. ```APIDOC ## GET getCurrentMember ### Description Fetches the data for the currently logged-in member. Returns null if no member is authenticated. ### Method GET ### Endpoint memberstack.getCurrentMember(options?) ### Parameters #### Query Parameters - **useCache** (boolean) - Optional - Set true to use cached data ### Response #### Success Response (200) - **data** (Member | null) - The member object or null #### Response Example { "data": { "id": "mem_123", "auth": { "email": "user@example.com" }, "planConnections": [] } } ``` -------------------------------- ### GET /v2/data-tables Source: https://developers.memberstack.com/admin-rest-api/data-tables Retrieve a list of all data tables configured in your Memberstack application. ```APIDOC ## GET /v2/data-tables ### Description Retrieve all data tables in your application. ### Method GET ### Endpoint https://admin.memberstack.com/v2/data-tables ### Parameters #### Headers - **x-api-key** (string) - Required - Your Memberstack secret key. ### Request Example curl --location --request GET 'https://admin.memberstack.com/v2/data-tables' \ --header 'x-api-key: sk_sb_your_secret_key' ### Response #### Success Response (200) - **data** (array) - List of data table objects. #### Response Example { "data": [ { "id": "table_123", "name": "Products", "key": "products" } ] } ``` -------------------------------- ### Memberstack Server-Side Admin Package Initialization (JavaScript) Source: https://memberstack.com/llms-full.txt Demonstrates how to initialize the Memberstack server-side admin package using JavaScript. This involves importing the package and calling the init function with your Memberstack SECRET key, emphasizing the use of environment variables for security. ```javascript import memberstackAdmin from '@memberstack/admin'; // Initialize with your SECRET key (not public key!) const memberstack = memberstackAdmin.init(process.env.MEMBERSTACK_SECRET_KEY); ``` -------------------------------- ### GET /data-tables Source: https://developers.memberstack.com/llms.txt Retrieves a list of all available data tables within the Memberstack project. ```APIDOC ## GET /data-tables ### Description List all data tables available in the project. ### Method GET ### Endpoint /getDataTables() ### Response #### Success Response (200) - **tables** (array) - List of table objects containing schema and metadata. ``` -------------------------------- ### GET /findUnique Source: https://developers.memberstack.com/admin-rest-api/data-tables Retrieves a single record by its unique ID. Note that this method is restricted to ID-based lookups and does not support pagination or ordering. ```APIDOC ## GET /records/{id} ### Description Retrieves a single record from the database using its unique identifier. ### Method GET ### Endpoint /records/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the record. ### Request Example GET /records/cm8abc123yza234ghi ### Response #### Success Response (200) - **data** (object) - The record object containing id, internalOrder, timestamps, and data fields. #### Response Example { "data": { "record": { "id": "cm8abc123yza234ghi", "internalOrder": 12345, "createdAt": "2024-01-25T09:15:00.000Z", "data": { "name": "Premium Widget", "price": 29.99 } } } } ``` -------------------------------- ### Get Data Table Source: https://developers.memberstack.com/admin-rest-api/data-tables Retrieve a specific data table by its key or ID. This endpoint is useful for inspecting the schema and configuration of a table. ```APIDOC ## Get Data Table ### Description Retrieve a specific data table by key or ID. ### Method GET ### Endpoint https://admin.memberstack.com/v2/data-tables/:tableKey ### Parameters #### Path Parameters - **tableKey** (string) - Required - The key or ID of the data table to retrieve (e.g., `products` or `tbl_cm1abc123def456`). ### Request Example Using curl: ```bash curl --location --request GET 'https://admin.memberstack.com/v2/data-tables/products' \ --header 'x-api-key: sk_sb_your_secret_key' ``` Using Axios: ```javascript const axios = require('axios'); const API_KEY = process.env.MEMBERSTACK_SECRET_KEY; const BASE_URL = 'https://admin.memberstack.com/v2/data-tables'; const headers = { "X-API-KEY": API_KEY }; // Get by table key const response = await axios.get(`${BASE_URL}/products`, { headers }); // Or get by table ID const responseById = await axios.get(`${BASE_URL}/tbl_cm1abc123def456`, { headers }); ``` ### Response #### Success Response (200) - **data** (object) - Contains the table details including its fields, rules, and metadata. #### Response Example ```json { "data": { "id": "tbl_cm1abc123def456", "key": "products", "name": "Products", "createRule": "AUTHENTICATED", "readRule": "PUBLIC", "updateRule": "AUTHENTICATED_OWN", "deleteRule": "ADMIN_ONLY", "createdAt": "2024-01-15T10:30:00.000Z", "updatedAt": "2024-01-20T14:45:00.000Z", "fields": [ { "id": "cm2xyz789ghi012abc", "key": "name", "name": "Product Name", "type": "TEXT", "required": true, "defaultValue": null, "tableOrder": 0, "referencedTableId": null } ] } } ``` ``` -------------------------------- ### Open and Hide Memberstack Modals (JavaScript) Source: https://developers.memberstack.com/llms.txt Demonstrates how to use the `memberstack.openModal()` and `memberstack.hideModal()` functions to control pre-built modals like login, signup, profile, and password reset. The signup modal accepts an optional configuration object for specifying plans. ```javascript memberstack.openModal("LOGIN"); memberstack.openModal("SIGNUP", { signup: { plans: ["pln_free-id"] } }); // Note: array of strings, not objects memberstack.openModal("PROFILE"); memberstack.openModal("FORGOT_PASSWORD"); memberstack.openModal("RESET_PASSWORD"); memberstack.hideModal(); ``` -------------------------------- ### Implement Passwordless Authentication with Memberstack Source: https://memberstack.com/llms-full.txt Demonstrates how to trigger passwordless emails for login and signup, and how to finalize the authentication process using the received 6-digit token. These methods require a valid email address and handle the state transition for new or existing members. ```javascript try { await memberstack.sendMemberLoginPasswordlessEmail({ email: "user@example.com", redirectUrl: window.location.origin + "/dashboard" }); } catch (error) { console.error(error.message); } try { const result = await memberstack.loginMemberPasswordless({ email: "user@example.com", passwordlessToken: "123456" }); } catch (error) { console.error(error.message); } ``` -------------------------------- ### Initialize Theme Preference Script Source: https://developers.memberstack.com/admin-node-package A client-side script to detect and apply the user's preferred color scheme (dark or light mode) from local storage or system settings. ```javascript (function() { const stored = localStorage.getItem('theme'); if (stored === 'dark' || (!stored && window.matchMedia('(prefers-color-scheme: dark)').matches)) { document.documentElement.classList.add('dark'); } })(); ``` -------------------------------- ### Parse Memberstack Custom Fields Source: https://memberstack.com/llms-full.txt Demonstrates how to correctly parse custom field data retrieved from Memberstack, as all custom fields are stored as strings. Includes examples for parsing integers and JSON strings. ```javascript const age = parseInt(member.customFields.age); const preferences = JSON.parse(member.customFields.preferences); ``` -------------------------------- ### Retrieve All and Single Plans with Memberstack Source: https://memberstack.com/llms-full.txt Shows how to fetch all available plans or a specific plan's details using the Memberstack SDK. Handles potential errors during the API calls and logs the retrieved plan information. Requires the Memberstack SDK. ```javascript // GET all plans try { const { data: plans } = await memberstack.getPlans(); console.log("Available plans:", plans); plans.forEach(plan => { console.log(`${plan.name} (${plan.id})`); plan.prices?.forEach(price => { console.log(` - ${price.name}: ${price.amount} ${price.currency}/${price.interval}`); }); }); } catch (error) { console.error("Failed to get plans:", error.message); } // GET single plan try { const { data: plan } = await memberstack.getPlan({ planId: 'pln_premium-plan-id' }); console.log("Plan details:", plan); } catch (error) { console.error("Failed to get plan:", error.message); } ``` -------------------------------- ### Initialize Memberstack in SvelteKit Source: https://memberstack.com/llms-full.txt Sets up Svelte stores for member data and loading state, initializes the Memberstack DOM client, and handles authentication changes. It's designed to be called once, typically in a layout component. ```javascript // stores/memberstack.js import { writable } from 'svelte/store'; import memberstackDOM from '@memberstack/dom'; import { browser } from '$app/environment'; export const member = writable(null); export const loading = writable(true); let memberstackInstance = null; let authListener = null; export function initMemberstack() { if (!browser) return null; if (!memberstackInstance) { memberstackInstance = memberstackDOM.init({ publicKey: import.meta.env.VITE_MEMBERSTACK_KEY, useCookies: true }); authListener = memberstackInstance.onAuthChange((m) => { member.set(m); loading.set(false); }); memberstackInstance.getCurrentMember().then(({ data }) => { member.set(data); loading.set(false); }); } return memberstackInstance; } export function getMemberstack() { return memberstackInstance; } // Usage in +layout.svelteLoading...
{:else if $member}Welcome, {$member.auth.email}
{:else} {/if} ``` -------------------------------- ### Memberstack Initialization Source: https://memberstack.com/llms-full.txt Initializes the Memberstack DOM package with your public key and configuration options. ```APIDOC ## Memberstack Initialization ### Description Initializes the Memberstack DOM package. This is a required step before making any other Memberstack calls. ### Method `memberstackDOM.init(config)` ### Endpoint N/A (Client-side initialization) ### Parameters #### Request Body - **publicKey** (string) - Required - Your Memberstack public key (e.g., `pk_your_public_key_here`). - **useCookies** (boolean) - Optional - Defaults to `false`. Enables cookie-based authentication. - **setCookieOnRootDomain** (boolean) - Optional - Defaults to `false`. Requires `useCookies: true`. Sets cookies on the root domain for subdomain sharing. - **domain** (string) - Optional - Defaults to Memberstack API. A custom API domain. ### Request Example ```javascript import memberstackDOM from '@memberstack/dom'; const memberstack = memberstackDOM.init({ publicKey: 'pk_your_public_key_here', useCookies: true, setCookieOnRootDomain: true, domain: 'https://custom-api.example.com' }); ``` ### Response #### Success Response (200) Returns the initialized Memberstack instance. #### Response Example ```javascript // memberstack instance is returned and available for further calls ``` ``` -------------------------------- ### Initialize Memberstack SDK Source: https://memberstack.com/llms-full.txt Configures the Memberstack instance using a public key. It supports optional cookie-based authentication and cross-subdomain sharing. ```javascript const memberstack = memberstackDOM.init({ publicKey: 'pk_...', useCookies: true, setCookieOnRootDomain: true }); ``` -------------------------------- ### Remove Plan from Member with Memberstack Source: https://memberstack.com/llms-full.txt Provides a code example for removing a plan from a member's account using the Memberstack SDK. It requires the Plan ID of the plan to be removed. The function returns the updated member object and includes error handling. ```javascript try { const result = await memberstack.removePlan({ planId: "pln_plan-to-remove" }); console.log("Plan removed:", result.data.member.planConnections); } catch (error) { console.error("Failed to remove plan:", error.message); } ``` -------------------------------- ### List Available Memberstack Projects Source: https://developers.memberstack.com/mcp-server Lists all available Memberstack projects for the authenticated user. This is useful for identifying the correct App ID to use when switching contexts. ```javascript memberstack.listApps() ``` -------------------------------- ### JavaScript / npm Initialization Source: https://developers.memberstack.com/llms.txt Initialize the Memberstack DOM SDK for use with JavaScript frameworks like React, Next.js, Vue, and Svelte. ```APIDOC ## Initialize Memberstack SDK ### Description Initializes the `@memberstack/dom` SDK with your public key and optional settings. ### Method `memberstackDOM.init(options)` ### Parameters - **options** (object) - Required - Configuration options for initialization. - **publicKey** (string) - Required - Your Memberstack public API key. - **useCookies** (boolean) - Optional - Enable cookie-based authentication. ### Request Example ```javascript import memberstackDOM from '@memberstack/dom'; const memberstack = memberstackDOM.init({ publicKey: 'pk_your_public_key_here', useCookies: true }); ``` ### Response Returns a Memberstack instance with available methods. ``` -------------------------------- ### Get Current Member Data with Memberstack Source: https://memberstack.com/llms-full.txt Retrieves the currently logged-in member's data. It can optionally use cached data to improve performance. The function returns member details including ID, email, verification status, plans, custom fields, and profile image. Handles cases where no member is logged in. ```javascript try { const { data: member } = await memberstack.getCurrentMember(); if (member) { console.log("Member is logged in"); console.log("ID:", member.id); console.log("Email:", member.auth.email); console.log("Verified:", member.verified); console.log("Plans:", member.planConnections); console.log("Custom fields:", member.customFields); console.log("Profile image:", member.profileImage); const hasPremium = member.planConnections?.some( conn => conn.planId === 'pln_premium' && conn.active ); } else { console.log("No member logged in"); } } catch (error) { console.error("Failed to get member:", error.message); } ``` -------------------------------- ### Querying Records with Filters and Sorting (JavaScript) Source: https://developers.memberstack.com/admin-rest-api/data-tables Demonstrates how to fetch multiple records with specific filter conditions and sorting applied. It uses axios to send a POST request to the API endpoint. Dependencies include axios and a BASE_URL constant. ```javascript const response = await axios.post(`${BASE_URL}/products/records/query`, { query: { findMany: { where: { inStock: true, price: { gte: 20, lte: 100 } }, orderBy: { price: 'asc' }, take: 10 } } }, { headers }); ``` -------------------------------- ### Initialize Memberstack DOM Client Source: https://memberstack.com/llms-full.txt Initializes the Memberstack DOM client with essential configuration options. This must be done before any other Memberstack calls. Key options include publicKey, useCookies, setCookieOnRootDomain, and domain. ```javascript import memberstackDOM from '@memberstack/dom'; // Initialize Memberstack (REQUIRED before any other calls) const memberstack = memberstackDOM.init({ publicKey: 'pk_your_public_key_here', // REQUIRED - get from Memberstack dashboard useCookies: true, // Optional: enable cookie-based auth (default: false) setCookieOnRootDomain: true, // Optional: set cookies on root domain (requires useCookies: true) domain: 'https://custom-api.example.com' // Optional: custom API domain }); ``` -------------------------------- ### Initialize Memberstack in Next.js (App Router) Source: https://memberstack.com/llms-full.txt Provides a React context provider for Memberstack, managing member state and loading status. It initializes the Memberstack DOM client and sets up an authentication listener. Usage requires wrapping the application with the provider. ```javascript // lib/memberstack.js 'use client'; import { createContext, useContext, useEffect, useState } from 'react'; import memberstackDOM from '@memberstack/dom'; const MemberstackContext = createContext(null); let memberstackInstance = null; export function MemberstackProvider({ children }) { const [member, setMember] = useState(null); const [loading, setLoading] = useState(true); useEffect(() => { if (!memberstackInstance) { memberstackInstance = memberstackDOM.init({ publicKey: process.env.NEXT_PUBLIC_MEMBERSTACK_KEY, useCookies: true }); } const authListener = memberstackInstance.onAuthChange((m) => { setMember(m); setLoading(false); }); memberstackInstance.getCurrentMember().then(({ data }) => { setMember(data); setLoading(false); }); return () => authListener.unsubscribe(); }, []); return (Welcome, {member.auth.email}
) : ( ); } ``` -------------------------------- ### Memberstack Email/Password Signup Source: https://memberstack.com/llms-full.txt Handles member signup using email and password with Memberstack. Supports optional parameters like custom fields, metadata, plan assignments, and invite tokens. Returns a promise with member data and access tokens upon successful signup. Includes error handling for common issues like existing emails or weak passwords. ```javascript // METHOD: memberstack.signupMemberEmailPassword(params, options?) // REQUIRED params: { email: string, // Member's email address password: string // Member's password (minimum 8 characters) } // OPTIONAL params: { customFields?: object, metaData?: object, plans?: Array<{ planId: string }>, // CRITICAL: Array of OBJECTS with planId captchaToken?: string, inviteToken?: string } // RETURNS: Promise<{ data: { member: Member, tokens: { accessToken: string } } }> // COMPLETE EXAMPLE: try { const result = await memberstack.signupMemberEmailPassword({ email: "user@example.com", password: "securePassword123", customFields: { firstname: "John", lastname: "Doe", company: "Acme Inc" }, plans: [{ planId: "pln_free-plan-id" }] // CRITICAL: Array of objects, NOT strings }); console.log("Signup successful:", result.data.member); console.log("Member ID:", result.data.member.id); console.log("Email:", result.data.member.auth.email); // Note: .auth.email console.log("Access token:", result.data.tokens.accessToken); // Redirect to dashboard or show welcome message window.location.href = '/dashboard'; } catch (error) { console.error("Signup failed:", error.message); // Handle specific errors if (error.code === 'email-already-in-use') { alert('An account with this email already exists.'); } else if (error.code === 'invalid-password-too-short') { alert('Password is too weak. Use at least 8 characters.'); } } ``` -------------------------------- ### POST /openModal Source: https://memberstack.com/llms-full.txt Opens a pre-built Memberstack modal such as Login, Signup, or Profile management. ```APIDOC ## POST /openModal ### Description Triggers the display of a specific Memberstack modal. Supported types: LOGIN, SIGNUP, PROFILE, FORGOT_PASSWORD, RESET_PASSWORD. ### Method POST ### Endpoint memberstack.openModal(type, params?) ### Parameters #### Path Parameters - **type** (string) - Required - The modal identifier. #### Request Body - **params** (object) - Optional - Configuration object for the modal, such as signup plans. ### Request Example { "type": "SIGNUP", "params": { "signup": { "plans": ["pln_123"] } } } ### Response #### Success Response (200) - **result** (object) - Returns the outcome of the modal interaction upon resolution. ``` -------------------------------- ### Core MCP Environment Management Source: https://developers.memberstack.com/mcp-server Tools for managing project contexts and switching between LIVE and SANDBOX environments. ```APIDOC ## Environment & Context Management ### Description Manage project-specific contexts and ensure operations are performed in the correct environment (LIVE vs. SANDBOX). ### Key Tools - **listApps**: Retrieve all accessible Memberstack projects. - **switchApp**: Set the active project context. - **currentApp**: Verify the currently selected project. - **getMemberstackEnvironment**: Check if currently in LIVE or SANDBOX. - **switchMemberstackEnvironment**: Toggle between testing and production environments. ### Best Practice Always verify your environment before executing write operations to avoid accidental production data modification. ``` -------------------------------- ### Memberstack Development Best Practices Source: https://memberstack.com/llms-full.txt Critical notes and common patterns for developers using Memberstack SDKs. ```APIDOC ## Development Notes ### Member JSON Updates Member JSON updates replace the existing object. Always fetch, merge, and update. ```javascript // CORRECT - fetch, merge, update: const { data } = await memberstack.getMemberJSON(); await memberstack.updateMemberJSON({ json: { ...data, theme: "dark" } }); ``` ### Data Tables `updateDataRecord()` performs a partial update; fetching the existing record is not required. ### Property Paths - Use `member.auth.email` and `member.planConnections`. - Avoid `member.data.email` or `member.plans`. ``` -------------------------------- ### Initialize Memberstack SDK Source: https://developers.memberstack.com/llms.txt Initializes the Memberstack client-side SDK. This is required for all JavaScript-based applications to enable authentication and gating features. ```javascript import memberstackDOM from '@memberstack/dom'; const memberstack = memberstackDOM.init({ publicKey: 'pk_your_public_key_here', useCookies: true }); ``` -------------------------------- ### Email/Password Signup Source: https://memberstack.com/llms-full.txt Allows members to sign up using their email and password, with options for custom fields and plan assignments. ```APIDOC ## Email/Password Signup ### Description Enables members to create an account using their email address and a password. Supports custom fields, metadata, plan assignments, and CAPTCHA/invite tokens. ### Method `memberstack.signupMemberEmailPassword(params, options?)` ### Endpoint N/A (Client-side method) ### Parameters #### Request Body - **email** (string) - Required - The member's email address. - **password** (string) - Required - The member's password (minimum 8 characters). - **customFields** (object) - Optional - An object containing custom fields for the member (e.g., `{ firstname: 'John', lastname: 'Doe' }`). - **metaData** (object) - Optional - Additional metadata to associate with the member. - **plans** (Array<{ planId: string }>) - Optional - CRITICAL: An array of objects, where each object contains a `planId` to assign to the member (e.g., `[{ planId: 'pln_free-plan-id' }]`). - **captchaToken** (string) - Optional - A CAPTCHA token if CAPTCHA is enabled for signups. - **inviteToken** (string) - Optional - An invite token for restricted signups. ### Request Example ```javascript try { const result = await memberstack.signupMemberEmailPassword({ email: "user@example.com", password: "securePassword123", customFields: { firstname: "John", lastname: "Doe", company: "Acme Inc" }, plans: [{ planId: "pln_free-plan-id" }] }); console.log("Signup successful:", result.data.member); window.location.href = '/dashboard'; } catch (error) { console.error("Signup failed:", error.message); if (error.code === 'email-already-in-use') { alert('An account with this email already exists.'); } } ``` ### Response #### Success Response (200) - **data** (object) - Contains member and token information. - **member** (object) - The newly created member object. - **id** (string) - The unique identifier for the member. - **auth** (object) - Authentication details. - **email** (string) - The member's email address. - **tokens** (object) - Authentication tokens. - **accessToken** (string) - The access token for the member's session. #### Response Example ```json { "data": { "member": { "id": "mbr_xxxxxxxxxxxxxx", "auth": { "email": "user@example.com" } }, "tokens": { "accessToken": "at_xxxxxxxxxxxxxx" } } } ``` ``` -------------------------------- ### Create Data Record using Axios Source: https://developers.memberstack.com/admin-rest-api/data-tables Demonstrates creating a new data record in a Memberstack table using Axios in JavaScript. The function sends a POST request with the record data in the request body. It includes setting the necessary headers for authentication and content type. ```javascript const axios = require('axios'); const API_KEY = process.env.MEMBERSTACK_SECRET_KEY; const BASE_URL = 'https://admin.memberstack.com/v2/data-tables'; const headers = { "X-API-KEY": API_KEY, "Content-Type": "application/json" }; const response = await axios.post(`${BASE_URL}/products/records`, { data: { name: "Premium Widget", price: 29.99, inStock: true, category: "cm6cat001stu678abc" // Reference to another record } }, { headers }); console.log(response.data); ``` -------------------------------- ### Add Free Plan to Member with Memberstack Source: https://memberstack.com/llms-full.txt Demonstrates how to add a free plan to a member's account using the Memberstack SDK. It requires the Plan ID of the free plan. The function returns the updated member object upon successful addition. Error handling is included. ```javascript try { const result = await memberstack.addPlan({ planId: "pln_free-tier-id" // Use Plan ID for free plans }); console.log("Plan added:", result.data.member.planConnections); } catch (error) { console.error("Failed to add plan:", error.message); } ``` -------------------------------- ### Using Logical Operators for Complex Queries (JavaScript) Source: https://developers.memberstack.com/admin-rest-api/data-tables Demonstrates how to construct complex filter conditions using logical operators like `OR` and `AND`. This allows for more sophisticated querying by combining multiple criteria. Requires axios and BASE_URL. ```javascript const response = await axios.post(`${BASE_URL}/products/records/query`, { query: { findMany: { where: { OR: [ { price: { lt: 10 } }, { AND: [ { price: { gte: 50 } }, { inStock: true } ]} ] } } } }, { headers }); ```