The Memberstack Admin Package for Node.js provides an easy way to build robust user management and authentication into your Node.js applications. With the package, you can programmatically manage members, plans, and security integrations with Memberstack using simple JavaScript functions.
This eliminates the need to build these common user management features from scratch or make raw Admin API calls yourself. The package handles all the underlying API requests, authentication, and response parsing.
This guide covers everything you need to get started using the Admin Package in your Node.js app. It includes:
- An overview of the package's capabilities
- Installation and initialization instructions
- Details on secret keys and authentication
- Examples for core tasks like managing members and plans
- Explanations of helper methods for verification
Whether you're looking to quickly prototype something or build a complex, production-ready application, this guide will provide the essentials for integrating Memberstack's user infrastructure through the Admin Package.
View the full Admin Package Website for more additional guidance.
1) Overview
The Admin Package is an npm module that wraps Memberstack's Admin API. It makes it easy to:
- Authenticate requests with your secret key
- List, create, update, and delete members
- Manage member plans
- Verify member tokens and webhook signatures
2) Installation
npm install @memberstack/admin
3) Secret Keys
Memberstack uses secret keys to authenticate API requests. There are two types of secret keys:
-
Test keys - Start with
sk_sb_. Use for development/testing. -
Live keys - Start with
sk_. Use in production.
Keep your secret keys secure and confidential. Only use them server-side.
4) Rate Limits
The API is rate limited to 25 requests per second. Memberstack will not increase the rate limits.
5) Import and Initialize
import memberstackAdmin from "@memberstack/admin";
// Initialize with secret key
const memberstack = memberstackAdmin.init('sk_...');6) Working with Members
List Members
Accepts pagination parameters:
-
limit- Number of members to return -
after- TheendCursorfrom the previous page (a number) -
order- 'ASC' or 'DESC'// First page const { data: members, hasNextPage, endCursor } = await memberstack.members.list({ limit: 10, order: 'ASC' // or 'DESC' (newest first) }); // Next page: pass the endCursor from the previous response if (hasNextPage) { const { data: nextMembers } = await memberstack.members.list({ limit: 10, after: endCursor, order: 'ASC' }); }
Get a Member
Pass member id or email:
const { data: member } = await memberstack.members.retrieve({ id: 'abc123' });
// or by email
const { data: memberByEmail } = await memberstack.members.retrieve({ email: 'john@gmail.com' });
// data is null when no member matchesCreate a Member
Requires email and password (at least 8 characters). Can also pass:
-
customFields- Object of custom fields (keys must be custom fields defined in your app; others are ignored) -
metaData- Object of metadata -
json- Object of custom JSON -
loginRedirect- URL to redirect after loginconst { data: member } = await memberstack.members.create({ email: 'john@gmail.com', password: 'a-long-password', // at least 8 characters customFields: { name: 'John Doe' // keys must be custom fields defined in your app; others are ignored }, metaData: { lang: 'en' }, loginRedirect: '/welcome' });
Update a Member
Pass member id and data to update:
await memberstack.members.update({
id: 'abc123',
data: {
customFields: {
name: 'Jane Doe'
}
}
});Delete a Member
Pass member id to delete:
await memberstack.members.delete({ id: 'abc123' });7) Plans, Webhooks, Tokens
Helper methods include:
Manage Plans
// Add a free plan
await memberstack.members.addFreePlan({
id: 'abc123',
data: { planId: 'plan123' }
});
// Remove a free plan
await memberstack.members.removeFreePlan({
id: 'abc123',
data: { planId: 'plan123' }
});Verify Webhooks
// Verify webhook signature: returns true, or throws if the request is not from Memberstack
memberstack.verifyWebhookSignature({
headers: req.headers, // from @memberstack/admin 1.8.0; on 1.7.0 and earlier, see below
secret: "whsec_...",
payload: req.body, // the parsed JSON body
tolerance: 300
});Common Issues with Webhook Verification
There are a few common issues when verifying webhook signatures:
-
Header Case Sensitivity: In
@memberstack/admin1.7.0 and earlier, the method expects the header keys in all caps (SVIX-ID,SVIX-TIMESTAMP,SVIX-SIGNATURE) even though they arrive in lowercase, so map them as in the example below. From 1.8.0 any case works and you can passreq.headersdirectly. -
Payload Format: Pass the whole parsed JSON body (
req.bodyafter a JSON body parser such asexpress.json()), notreq.body.payloadand not the raw string.
Example Implementation:
const memberstackAdmin = require('@memberstack/admin');
const memberstack = memberstackAdmin.init(process.env.MEMBERSTACK_API_KEY);
// Use with a JSON body parser, e.g. app.post('/webhook', express.json(), handleWebhook)
const handleWebhook = async (req, res) => {
try {
const secret = process.env.MEMBERSTACK_WEBHOOK_SECRET; // whsec_..., from your webhook in the Memberstack dashboard
// Uppercase keys work with every version (1.7.0 and earlier require them)
const headers = {
"SVIX-ID": req.headers['svix-id'],
"SVIX-SIGNATURE": req.headers['svix-signature'],
"SVIX-TIMESTAMP": req.headers['svix-timestamp'],
}
// Returns true, or throws if the signature or timestamp is not valid
memberstack.verifyWebhookSignature({
headers: headers,
secret: secret,
payload: req.body,
tolerance: 300
});
console.log("webhook verified");
// Process the webhook data here
return res.status(200).send('Webhook received and processed');
} catch (error) {
console.error('Verification error:', error.message);
return res.status(400).send('Webhook verification failed');
}
};Verify Tokens
// Verify and decode a member token (from the _ms-mid cookie or an Authorization header)
const { id } = await memberstack.verifyToken({
token: 'jwt123',
audience: 'app_...' // your app ID: without it, tokens from other Memberstack apps also pass
});
// id is the member ID. The result also has type ("member"), iat, exp, aud and iss, but no email:
// use memberstack.members.retrieve({ id }) for the member's details.
Comments
No comments yet. Start the conversation below.
Please sign in to leave a comment.