Verification
The Memberstack Admin Package provides essential verification functionality for secure server-side operations, including token verification and webhook validation. These features are crucial for maintaining security in your Memberstack implementation.
- Make sure you’ve initialized the Admin Package with your secret key as shown in the Quick Start guide
- For webhook verification, you’ll need your webhook secret from the Memberstack dashboard (Dev Tools → Webhooks)
- Understanding of JWT tokens is helpful for token verification
Verify Member Token
Validate a member’s JWT token and access the payload.
The verifyToken() method allows you to validate Memberstack JWT tokens and extract member information:
// Basic token verification
const tokenData = await memberstack.verifyToken({
token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
});
// With audience validation (recommended)
const tokenData = await memberstack.verifyToken({
token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
audience: "app_your_app_id"
});
if (tokenData) {
console.log(`Verified member ID: ${tokenData.id}`);
console.log(`Token expires at: ${new Date(tokenData.exp * 1000).toLocaleString()}`);
}{
id: "mem_abc123",
type: "member",
iat: 1633486880169, // Issued at timestamp
exp: 1633486880369, // Expiration timestamp
iss: "https://api.memberstack.com", // Issuer
aud: "app_xyz789" // Audience (your app ID)
}Token Verification Parameters.
Best practices for token verification:
- Always include audience validation when possible
- Implement proper error handling for expired or invalid tokens
- Check the token expiration time to handle near-expiry scenarios
- Store the member ID from the token for database lookups
Using the Token in Your Application
Here’s an example of how to create an Express.js middleware for authenticating member requests:
// auth.middleware.js
const memberstackAdmin = require('@memberstack/admin');
const memberstack = memberstackAdmin.init(process.env.MEMBERSTACK_SECRET_KEY);
/**
* Express middleware to verify Memberstack authentication
*/
async function requireAuth(req, res, next) {
try {
// Extract token from Authorization header
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.status(401).json({ error: 'Authentication required' });
}
const token = authHeader.split(' ')[1];
// Verify the token
const verifiedToken = await memberstack.verifyToken({
token,
audience: process.env.MEMBERSTACK_APP_ID
});
// Add member data to the request object
req.member = verifiedToken;
// Token is valid, proceed
next();
} catch (error) {
console.error('Authentication error:', error.message);
// Determine the appropriate error response
if (error.message.includes('expired')) {
return res.status(401).json({ error: 'Authentication expired' });
}
return res.status(401).json({ error: 'Invalid authentication' });
}
}
module.exports = { requireAuth };- Expired tokens: The token has passed its expiration time and is no longer valid
- Invalid signature: The token has been tampered with or was created with a different key
- Audience mismatch: The token was issued for a different application than expected
- Format errors: The token is malformed or doesn’t follow JWT standards
Verify Webhook Signature
Ensure webhook payloads are authentic and haven’t been tampered with.
Memberstack uses Svix under the hood for secure webhook delivery. This section explains how to properly verify incoming webhook requests to ensure they are legitimate and haven’t been tampered with.
Memberstack webhook verification requires specific headers that are sent with each webhook request:
svix-id- Unique identifier for the webhook eventsvix-timestamp- When the webhook was sentsvix-signature- The cryptographic signature for verification
When you pass these to verifyWebhookSignature, the headers object must be keyed in uppercase — SVIX-ID, SVIX-TIMESTAMP, and SVIX-SIGNATURE — which is the exact key the SDK looks up. Read the values from the incoming request headers (which arrive in lowercase) as shown in the example below. Previous header formats (like ms-webhook-id) are no longer supported.
verifyWebhookSignature returns true when the signature is valid and throws an error on any failure — missing svix headers, a timestamp outside the tolerance window, or a signature mismatch. It never returns false, so there is no falsy value to test. Call it inside a try/catch and treat any thrown error as an invalid webhook (reject with 401); don’t branch on its return value or you’ll let forged requests through.
Basic Verification Example
Here’s how to verify a webhook signature in an Express.js application:
// Express.js webhook verification example
const express = require('express');
const memberstackAdmin = require('@memberstack/admin');
const app = express();
const memberstack = memberstackAdmin.init(process.env.MEMBERSTACK_SECRET_KEY);
// Important: Use express.raw() to preserve the raw body for signature verification
app.post('/webhook', express.raw({ type: 'application/json' }), (req, res) => {
try {
// The raw body is needed for verification (don't parse to JSON first)
const payload = req.body.toString();
// verifyWebhookSignature looks these up by UPPERCASE key, so key the
// object SVIX-ID / SVIX-TIMESTAMP / SVIX-SIGNATURE. The incoming request
// header names are lowercase, hence req.headers['svix-id'].
const headers = {
'SVIX-ID': req.headers['svix-id'],
'SVIX-TIMESTAMP': req.headers['svix-timestamp'],
'SVIX-SIGNATURE': req.headers['svix-signature']
};
// Verify the webhook. verifyWebhookSignature returns true on success and
// THROWS on any failure (missing headers, timestamp out of tolerance, or a
// signature mismatch) — it never returns false. So if this call doesn't
// throw, the signature is valid; an invalid signature jumps to catch below.
memberstack.verifyWebhookSignature({
payload: JSON.parse(payload), // Parse the payload for processing after verification
headers: headers, // Pass the headers object
secret: process.env.MEMBERSTACK_WEBHOOK_SECRET // Your webhook secret from dashboard
});
// Webhook is verified, safe to process
const data = JSON.parse(payload);
console.log(`Verified webhook event: ${data.event}`);
// Process the webhook based on event type
switch (data.event) {
case 'member.created':
// Handle member creation
break;
case 'member.updated':
// Handle member update
break;
// Add more event types as needed
}
// Return a 200 response to acknowledge receipt
res.status(200).send('Webhook received and verified');
} catch (error) {
// A thrown error means verification failed (missing/invalid signature) — reject it.
console.error('Webhook verification failed:', error.message);
res.status(401).send('Invalid signature');
}
});- Use
express.raw()- Notexpress.json()for the webhook endpoint - Preserve the raw body - Modifying the body before verification will cause signature failure
- Header key casing -
verifyWebhookSignaturereads the headers by uppercase key (SVIX-ID,SVIX-TIMESTAMP,SVIX-SIGNATURE). Passing them lowercase triggers a “Please provide the svix-id, svix-timestamp, and svix-signature headers” error even when the headers are present - Correct webhook secret - Make sure you’re using the correct webhook secret from your dashboard (Dev Tools → Webhooks)
- Parse JSON after verification - Only parse the JSON payload after verifying the signature
Troubleshooting Header Errors
If you encounter the error "Please provide the svix-id, svix-timestamp, and svix-signature headers", follow these steps:
1. Debug the headers you’re receiving:
// Log all headers to see what's actually being received
console.log('All headers:', req.headers);2. Map the headers to the keys the SDK expects: verifyWebhookSignature looks them up by uppercase key, so build the object with SVIX-ID, SVIX-TIMESTAMP, and SVIX-SIGNATURE (reading the lowercase values Node provides):
// The SDK reads UPPERCASE keys; map the (lowercase) incoming headers to them
const headers = {
'SVIX-ID': req.headers['svix-id'],
'SVIX-TIMESTAMP': req.headers['svix-timestamp'],
'SVIX-SIGNATURE': req.headers['svix-signature']
};3. Don’t pass req.headers directly: Node lowercases incoming header names, but the SDK looks them up by uppercase key — so the raw req.headers object won’t match. Map to the uppercase keys (as above) before calling verifyWebhookSignature:
// Pass the UPPERCASE-keyed object from step 2 (not req.headers directly).
// verifyWebhookSignature returns true on success and throws on failure, so call
// it inside a try/catch rather than assigning and testing its return value.
memberstack.verifyWebhookSignature({
payload: JSON.parse(payload),
headers, // { 'SVIX-ID': ..., 'SVIX-TIMESTAMP': ..., 'SVIX-SIGNATURE': ... }
secret: process.env.MEMBERSTACK_WEBHOOK_SECRET
});Next.js API Route Example
For Next.js API routes, you’ll need to disable the built-in body parsing:
// pages/api/webhook.js
import memberstackAdmin from '@memberstack/admin';
// Initialize Memberstack outside the handler
const memberstack = memberstackAdmin.init(process.env.MEMBERSTACK_SECRET_KEY);
// Important: Disable body parsing
export const config = {
api: {
bodyParser: false,
},
};
export default async function handler(req, res) {
if (req.method !== 'POST') {
return res.status(405).json({ error: 'Method not allowed' });
}
try {
// Get the raw body
const chunks = [];
for await (const chunk of req) {
chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : chunk);
}
const rawBody = Buffer.concat(chunks).toString('utf8');
// Map to the UPPERCASE keys verifyWebhookSignature expects
const headers = {
'SVIX-ID': req.headers['svix-id'],
'SVIX-TIMESTAMP': req.headers['svix-timestamp'],
'SVIX-SIGNATURE': req.headers['svix-signature']
};
// Verify webhook. verifyWebhookSignature returns true on success and THROWS
// on any failure — it never returns false. If this call doesn't throw, the
// signature is valid; an invalid signature jumps to the catch block below.
memberstack.verifyWebhookSignature({
payload: JSON.parse(rawBody),
headers,
secret: process.env.MEMBERSTACK_WEBHOOK_SECRET
});
const data = JSON.parse(rawBody);
console.log(`Webhook event: ${data.event}`);
// Process webhook...
return res.status(200).json({ success: true });
} catch (error) {
// A thrown error means verification failed (missing/invalid signature) — reject it.
console.error('Webhook verification failed:', error.message);
return res.status(401).json({ error: 'Invalid signature' });
}
}- Always verify the webhook signature to prevent spoofing
- Implement idempotency using the webhook ID to prevent duplicate processing
- Store webhook events in a queue to ensure reliable processing
- Set up appropriate timeouts for webhook processing
- Return 2xx status codes promptly to acknowledge receipt (even if processing continues asynchronously)
- Rotate webhook secrets periodically for enhanced security
Finding Your Webhook Secret
To get your webhook secret:
- Log in to your Memberstack dashboard
- Navigate to "DevTools" > "Webhooks"
- Find or create your webhook endpoint
- Copy the "Signing Secret" value
Store this secret securely in your environment variables, not in your code.
Common Use Cases
Practical examples for implementing token verification.
Express.js Authentication Middleware
Here’s an example of creating a reusable middleware for authenticating requests in an Express.js application:
Next.js API Route Protection
Here’s how to protect API routes in a Next.js application:
Permission-Based Access Control
Implement role-based or permission-based access control by combining token verification with member data: