Skip to main content
Memberstack Docs
Dashboard

Frequently Asked Questions

This section addresses common questions and challenges when working with the Memberstack Admin Package. Find answers to technical questions, implementation strategies, and best practices.

/admin-node-package/faqs.md

The Admin and DOM packages serve different purposes and are used in different environments. The Admin Package is for server-side operations (Node.js): member management via your backend, webhook processing, token verification, and security-sensitive operations. The DOM Package is for client-side operations (browser): authentication UI, user registration and login, profile management, and payment processing. In a typical implementation, you would use both packages together: the DOM Package for client-side interactions and the Admin Package for server-side operations and security.

The Memberstack Admin API has a rate limit of 25 requests per second, counted per calling IP address. If you exceed this limit, the API answers HTTP 429 and the SDK call rejects with the plain string Too many requests, please try again later. (a string, not an error object, and with no status code).

For applications that need to process large numbers of members or handle high-traffic scenarios, implement these strategies: add delays between API calls in bulk operations; implement exponential backoff for retry logic; use batching for large datasets; cache frequently accessed data; and distribute operations over time when possible.

Here's an example of implementing exponential backoff for API calls:

/**
 * Retry a function with exponential backoff
 * @param {Function} fn - The function to retry
 * @param {number} maxRetries - Maximum number of retries
 * @param {number} baseDelay - Base delay in milliseconds
 * @returns {Promise<any>} - The function result
 */
async function retryWithBackoff(fn, maxRetries = 5, baseDelay = 300) {
  let retries = 0;

  while (true) {
    try {
      return await fn();
    } catch (error) {
      retries++;

      // The SDK rejects with the API's response body, which carries no HTTP status.
      // A rate-limit hit is the plain string 'Too many requests, please try again later.'
      const isRateLimited =
        typeof error === 'string' && error.toLowerCase().includes('too many requests');

      // If we've reached max retries or error isn't rate limiting, throw
      if (retries >= maxRetries || !isRateLimited) {
        throw error;
      }

      // Calculate exponential backoff delay
      const delay = baseDelay * Math.pow(2, retries);

      // Add some jitter to prevent synchronized retries
      const jitter = Math.random() * 100;

      console.log(`Rate limited. Retrying in ${delay + jitter}ms (attempt ${retries})`);

      // Wait before retrying
      await new Promise(resolve => setTimeout(resolve, delay + jitter));
    }
  }
}

// Usage example
async function getMemberWithRetry(memberId) {
  return retryWithBackoff(async () => {
    return await memberstack.members.retrieve({ id: memberId });
  });
}

If you're currently using direct REST API calls with fetch or axios, migrating to the Admin Package is straightforward. The Admin Package methods map closely to REST endpoints but provide better error handling, typed responses, and a more consistent developer experience.

REST API (Before)

// Using fetch to call the REST API directly
async function getMember(memberId) {
  try {
    const response = await fetch(`https://admin.memberstack.com/members/${memberId}`, {
      method: 'GET',
      headers: {
        'X-API-KEY': process.env.MEMBERSTACK_SECRET_KEY
      }
    });

    if (!response.ok) {
      throw new Error(`API error: ${response.status}`);
    }

    // { data: member }, or { data: null } when no member matches
    const body = await response.json();
    return body.data;
  } catch (error) {
    console.error('Error fetching member:', error);
    throw error;
  }
}
Admin Package (After)
// Using the Admin Package
const memberstackAdmin = require('@memberstack/admin');
const memberstack = memberstackAdmin.init(process.env.MEMBERSTACK_SECRET_KEY);

async function getMember(memberId) {
  try {
    const result = await memberstack.members.retrieve({
      id: memberId
    });

    // The member, or null when no member matches (retrieve does not throw for that)
    return result.data;
  } catch (error) {
    console.error('Error fetching member:', error.message);
    throw error;
  }
}
The Admin Package provides several benefits over direct REST API calls: a consistent API interface with proper typings (if using TypeScript); automatic error handling and parsing; simplified authentication (no need to manage auth headers); helper methods for common operations like webhook verification; and a better developer experience with IDE autocomplete.

Yes, the Admin Package is designed to work in any Node.js environment, including serverless functions like AWS Lambda, Vercel Serverless Functions, or Netlify Functions.

Serverless Considerations: Initialize the Memberstack client outside your handler function to take advantage of container reuse. Be mindful of cold starts, the initial initialization may add some latency to the first request. Store your secret key in environment variables or secrets management appropriate for your serverless platform. Consider connection pooling for database operations if you're using them.

Example of a properly structured AWS Lambda function using the Admin Package:

// Initialize Memberstack outside the handler
const memberstackAdmin = require('@memberstack/admin');
const memberstack = memberstackAdmin.init(process.env.MEMBERSTACK_SECRET_KEY);

// AWS Lambda handler
exports.handler = async (event) => {
  try {
    // Parse the request
    const memberId = event.pathParameters?.memberId;

    if (!memberId) {
      return {
        statusCode: 400,
        body: JSON.stringify({ error: 'Member ID is required' })
      };
    }

    // Get member details
    const result = await memberstack.members.retrieve({
      id: memberId
    });

    // retrieve() resolves { data: null } when no member matches (it does not throw)
    if (!result.data) {
      return {
        statusCode: 404,
        body: JSON.stringify({ error: 'Member not found' })
      };
    }

    // Return success response
    return {
      statusCode: 200,
      body: JSON.stringify(result.data)
    };
  } catch (error) {
    console.error('Error:', error);

    // Return error response. SDK errors are the API's response body
    // ({ code, message }) and carry no HTTP status.
    return {
      statusCode: 500,
      body: JSON.stringify({ error: error?.message || 'Internal server error' })
    };
  }
};

When an API call fails, the Admin Package rejects with the API's response body: normally a plain { code, message } object, which is not an Error instance and carries no HTTP status, so branch on error.code (and on error.message when the code is generic-message). Three cases behave differently: members.retrieve() does not reject for a missing member (it resolves { data: null }); a response that is not JSON (the rate-limit message, or a gateway error page) rejects with the body as a plain string; and a request that never got a response rejects with the underlying network Error.

try {
  // Attempt to update a member that doesn't exist
  await memberstack.members.update({
    id: "mem_does_not_exist",
    data: { verified: true }
  });
} catch (error) {
  if (typeof error === "string") {
    // A non-JSON response. A rate-limit hit is the string
    // "Too many requests, please try again later."
    if (error.toLowerCase().includes("too many requests")) {
      console.log("Rate limited:", error);
    } else {
      console.log("Unexpected response:", error);
    }
  } else if (error instanceof Error) {
    // The request never got a response (DNS failure, timeout, ...)
    console.log("Network error:", error.code, error.message);
  } else if (error?.code === "validation/invalid-secret-key") {
    console.log("Problem with your secret key");
  } else if (error?.message === "There is no member with this identifier.") {
    console.log("Member not found");
  } else {
    console.log("Other error:", error?.code, error?.message);
  }
}
Common Error Codes:
  • validation/invalid-secret-key - Missing, malformed, or unrecognized secret key
  • invalid-email / email-already-in-use - Creating or updating a member with a bad or taken email
  • invalid-password-too-short - Creating a member with a password under 8 characters
  • plan-not-found / plan-not-free / already-have-plan / no-plan-found - Adding or removing a plan
  • generic-message - Everything else; read message (for example There is no member with this identifier., Data table not found, Record not found)
Error Handling Best Practices: Always wrap API calls in try/catch blocks; check error.code to determine the type of error; check for null data after members.retrieve(); log detailed error information for debugging; provide user-friendly error messages in your application; and implement retry logic for transient errors (e.g., rate limits).

Memberstack provides a sandbox environment for testing your integration without affecting production data. The sandbox environment works exactly like the live environment but uses test credentials.

Test Mode Keys: Sandbox secret keys start with sk_sb_; found in your Memberstack dashboard under Developer → Keys & IDs with Test Mode enabled; limited to 50 test members; can be used for development and testing.

Live Mode Keys: Production secret keys start with sk_; for use in production environments only; no member limits; affects real customer data.

Testing approach using environment variables:

// .env.development
MEMBERSTACK_SECRET_KEY=sk_sb_your_test_key
// The app ID is the same in test and live mode; only the secret key changes
MEMBERSTACK_APP_ID=app_your_app_id

// .env.production
MEMBERSTACK_SECRET_KEY=sk_your_live_key
MEMBERSTACK_APP_ID=app_your_app_id

// Load the appropriate environment variables
const memberstackAdmin = require('@memberstack/admin');
const memberstack = memberstackAdmin.init(process.env.MEMBERSTACK_SECRET_KEY);
Important Testing Notes: Never use test mode data or keys in production environments; test data and live data are completely separate; create a complete testing plan that covers authentication, member operations, and webhooks; and use unique email addresses for test members to avoid conflicts.

Need help?
Can't find what you're looking for? Our team is here to help.