Skip to main content
Memberstack Docs
Dashboard

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.

/admin-node-package/verification.md
Before You Start
  • 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 (Developer → 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:

// Always pass your app ID as the audience. Member tokens for every
// Memberstack app share one signing key and issuer, so without audience a
// valid token issued for a DIFFERENT app also verifies.
const tokenData = await memberstack.verifyToken({
  token: "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIs...",
  audience: "app_your_app_id"
});

// verifyToken rejects (throws) on any failure, so reaching this line means
// the token is valid.
console.log(`Verified member ID: ${tokenData.id}`);
console.log(`Token expires at: ${new Date(tokenData.exp * 1000).toLocaleString()}`);
Token Verification Response
{
  id: "mem_abc123",
  type: "member",
  iat: 1763078400,  // Issued at (seconds since epoch)
  exp: 1764288000,  // Expires at (seconds since epoch)
  iss: "https://api.memberstack.com",  // Issuer
  aud: "app_xyz789"    // Audience (your app ID)
}
memberstack. verifyToken (params) async

Token Verification Parameters.

tokenstringRequired
The JWT token to verify (usually from Authorization header).
audiencestring
Your app ID. Always pass it: member tokens for every Memberstack app share one signing key and issuer, so without audience a valid token issued for a different app also verifies. If the value is undefined (for example a missing environment variable) the check is skipped silently.

Best practices for token verification:

  • Always pass audience (your app ID), and fail at startup if the environment variable that holds it is missing
  • 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
// 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
    // Make sure MEMBERSTACK_APP_ID is set: if audience is undefined, the
    // audience check is skipped and tokens from other apps also verify.
    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
    // verifyToken rejects with the jose error unchanged. An expired token has
    // code "ERR_JWT_EXPIRED" (its message does not contain the word "expired").
    if (error.code === 'ERR_JWT_EXPIRED') {
      return res.status(401).json({ error: 'Authentication expired' });
    }

    return res.status(401).json({ error: 'Invalid authentication' });
  }
}

module.exports = { requireAuth };
Common Token Issues
  • 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

Verifying Without the Admin Package

If you can’t use @memberstack/admin (a Cloudflare Worker, Deno, or a backend in another language), verify the token yourself with any JWT library. Memberstack publishes the public keys it signs member tokens with as a JSON Web Key Set at https://auth.memberstack.com/.well-known/member-jwks.json. It’s the same address verifyToken() uses from version 1.8.0, and no secret key is needed: the keys are public.

curl https://auth.memberstack.com/.well-known/member-jwks.json
# {"keys":[{"kty":"RSA","n":"...","e":"AQAB","alg":"RS256","use":"sig","kid":"..."}]}

A token is valid only if it passes every one of these checks:

CheckRule
SignatureRS256, with the key whose kid matches the token header
Issuer (iss)https://api.memberstack.com
Audience (aud)Your app ID (app_...)
Expiry (exp)Must be present and in the future
Type (type)"member"

The member ID is in the id claim; member tokens have no sub. Don’t skip the audience and type checks: Memberstack signs tokens for every app with the same key, so a correctly signed token may belong to a different app or not be a member token at all.

worker.js
// A Cloudflare Worker that only answers members of your app.
// Works in any runtime with fetch and Web Crypto. npm install jose
import { createRemoteJWKSet, jwtVerify } from 'jose';

// Create the key set once, outside the handler. jose caches the keys and
// fetches them again when a token names a key ID it hasn't seen.
const JWKS = createRemoteJWKSet(
  new URL('https://auth.memberstack.com/.well-known/member-jwks.json')
);

async function verifyMemberToken(token, appId) {
  const { payload } = await jwtVerify(token, JWKS, {
    issuer: 'https://api.memberstack.com',
    audience: appId, // your app ID; never leave it undefined
    algorithms: ['RS256'],
    requiredClaims: ['exp']
  });
  if (payload.type !== 'member') throw new Error('Not a member token');
  return payload.id; // the member ID, e.g. "mem_..."
}

export default {
  async fetch(request, env) {
    const auth = request.headers.get('Authorization') || '';
    const token = auth.startsWith('Bearer ') ? auth.slice(7) : '';
    try {
      const memberId = await verifyMemberToken(token, env.MEMBERSTACK_APP_ID);
      return new Response(`Hello, ${memberId}`);
    } catch {
      return new Response('Unauthorized', { status: 401 });
    }
  }
};
Caching and key changes
  • The key set can be cached for 10 minutes (it is served with Cache-Control: public, max-age=600)
  • If a token names a kid that isn’t in your cached copy, fetch the key set again: Memberstack publishes a new key at this address before signing tokens with it. jose’s createRemoteJWKSet does both for you
  • If your server can only reach approved hosts, allow HTTPS to auth.memberstack.com
Things to know
  • Logging out doesn’t revoke a token. Logout removes the token from the browser, but a copy of it keeps verifying until its exp, both here and with verifyToken(). If that matters for your app, keep its session duration short
  • auth.memberstack.com/jwks is a different key set. It holds the keys for Custom SSO (Memberstack as an identity provider), so member tokens never verify against it
  • Upgrade older Admin packages. @memberstack/admin 1.7.0 and earlier download the keys over plain HTTP from an S3 address. Version 1.8.0 uses the HTTPS address above

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.

Important Header Information

Memberstack webhook verification requires specific headers that are sent with each webhook request:

  • svix-id - Unique identifier for the webhook event
  • svix-timestamp - When the webhook was sent
  • svix-signature - The cryptographic signature for verification

From @memberstack/admin 1.8.0, verifyWebhookSignature matches these header keys in any case, so you can pass Node’s req.headers as is. Versions 1.7.0 and earlier only read the uppercase keys SVIX-ID, SVIX-TIMESTAMP, and SVIX-SIGNATURE, so the example below maps the incoming (lowercase) headers to them, which works with every version. The legacy ms-signature header is not accepted by verifyWebhookSignature (it is handled by the deprecated verifySignature).

How verification reports success or failure

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:

webhook.js
// 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);

// verifyWebhookSignature needs the PARSED body: it re-serializes the object
// with JSON.stringify to check the signature. express.json() gives you that.
app.post('/webhook', express.json(), (req, res) => {
  try {
    // The parsed JSON body. Do not add, remove or reorder keys before verifying.
    const data = req.body;

    // 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: data,                 // The parsed object (not the raw string)
      headers: headers,              // Pass the headers object
      secret: process.env.MEMBERSTACK_WEBHOOK_SECRET  // Your webhook secret from dashboard
    });

    // Webhook is verified, safe to process
    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');
  }
});
Common Verification Issues
  • Pass the parsed body - payload must be the parsed JSON object (req.body with express.json(), or JSON.parse(rawBody)). The SDK re-serializes it with JSON.stringify to check the signature, so passing the raw string or a Buffer always fails
  • Do not modify the object before verifying - Adding, removing or reordering keys changes the serialization and fails the check. Middleware that rewrites req.body (sanitizers, key-case converters) has the same effect
  • Header key casing - In @memberstack/admin 1.7.0 and earlier, verifyWebhookSignature reads the headers by uppercase key only (SVIX-ID, SVIX-TIMESTAMP, SVIX-SIGNATURE), so lowercase keys trigger a “Please provide the svix-id, svix-timestamp, and svix-signature headers” error even when the headers are present. Version 1.8.0 accepts any case
  • Correct webhook secret - Make sure you’re using the correct webhook secret from your dashboard (Developer → Webhooks)
  • Act only after verification - Do not use the payload for anything until verifyWebhookSignature has returned without throwing

Troubleshooting Header Errors

If you encounter the error "Please provide the svix-id, svix-timestamp, and svix-signature headers", follow these steps:

Header Troubleshooting

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. On 1.7.0 and earlier, don’t pass req.headers directly: Node lowercases incoming header names, but those versions look them up by uppercase key, so the raw req.headers object won’t match. Map to the uppercase keys (as above) before calling verifyWebhookSignature, or upgrade to 1.8.0, which accepts req.headers as is:

// 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: req.body, // the parsed JSON body (express.json())
  headers,  // { 'SVIX-ID': ..., 'SVIX-TIMESTAMP': ..., 'SVIX-SIGNATURE': ... }
  secret: process.env.MEMBERSTACK_WEBHOOK_SECRET
});

Next.js API Route Example

Next.js API routes parse JSON bodies for you, so you can pass req.body straight to verifyWebhookSignature. The example below turns the built-in parser off and reads the body itself, which also works:

pages/api/webhook.js
// pages/api/webhook.js
import memberstackAdmin from '@memberstack/admin';

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

// Optional: read the body yourself instead of using Next's parser
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' });
  }
}
Webhook Security Best Practices
  • 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:

  1. Log in to your Memberstack dashboard
  2. Navigate to "Developer" > "Webhooks"
  3. Find or create your webhook endpoint
  4. 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:

middleware/auth.js
// middleware/auth.js
const axios = require('axios');
require('dotenv').config();

const API_KEY = process.env.MEMBERSTACK_SECRET_KEY;
const BASE_URL = 'https://admin.memberstack.com/members';

/**
 * 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 with Memberstack
    const response = await axios.post(
      `${BASE_URL}/verify-token`,
      { token },
      {
        headers: {
          'X-API-KEY': API_KEY,
          'Content-Type': 'application/json'
        }
      }
    );

    // Add member data to the request object
    req.member = response.data.data;

    // Token is valid, proceed
    next();
  } catch (error) {
    console.error('Authentication error:', error.message);

    // verify-token answers 400 { code: "INVALID_TOKEN" } for every token
    // problem (expired, bad signature, wrong app); it does not say which.
    if (error.response?.data?.code === 'INVALID_TOKEN') {
      return res.status(401).json({ error: 'Invalid authentication' });
    }

    // Anything else (a 401 means YOUR secret key is wrong, a 429 means you
    // were rate limited) is not about the member's token.
    return res.status(502).json({ error: 'Could not verify authentication' });
  }
}

module.exports = { requireAuth };

// Usage in your routes
// routes/api.js
const express = require('express');
const router = express.Router();
const { requireAuth } = require('../middleware/auth');

// Public route - no authentication required
router.get('/public', (req, res) => {
  res.json({ message: 'This is a public endpoint' });
});

// Protected route - requires authentication
router.get('/protected', requireAuth, (req, res) => {
  res.json({
    message: 'This is a protected endpoint',
    memberId: req.member.id
  });
});

module.exports = router;

Next.js API Route Protection

Here’s how to protect API routes in a Next.js application:

pages/api/protected-data.js
// pages/api/protected-data.js
import axios from 'axios';

// Helper function to verify Memberstack token
async function verifyToken(token) {
  const API_KEY = process.env.MEMBERSTACK_SECRET_KEY;
  const BASE_URL = 'https://admin.memberstack.com/members';

  try {
    const response = await axios.post(
      `${BASE_URL}/verify-token`,
      { token },
      {
        headers: {
          'X-API-KEY': API_KEY,
          'Content-Type': 'application/json'
        }
      }
    );

    return response.data.data;
  } catch (error) {
    return null;
  }
}

export default async function handler(req, res) {
  // Get auth token from 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 memberData = await verifyToken(token);

  if (!memberData) {
    return res.status(401).json({ error: 'Invalid or expired token' });
  }

  // Check if token is expired
  const now = Math.floor(Date.now() / 1000);
  if (memberData.exp < now) {
    return res.status(401).json({ error: 'Token expired' });
  }

  // Token is valid, return protected data
  return res.status(200).json({
    message: 'Protected data accessed successfully',
    memberId: memberData.id,
    data: {
      // Your protected data here
      sensitiveInformation: 'This is protected content',
      memberSpecificData: `Data for member ${memberData.id}`
    }
  });
}

Permission-Based Access Control

Implement role-based or permission-based access control by combining token verification with member data:

middleware/rbac.js
// middleware/rbac.js
const axios = require('axios');
require('dotenv').config();

const API_KEY = process.env.MEMBERSTACK_SECRET_KEY;
const BASE_URL = 'https://admin.memberstack.com';

/**
 * Middleware to check if member has a required plan
 * @param {string} requiredPlanId - The plan ID to check for
 */
function requirePlan(requiredPlanId) {
  return async (req, res, next) => {
    try {
      // First ensure we have a verified member
      if (!req.member || !req.member.id) {
        return res.status(401).json({ error: 'Authentication required' });
      }

      // Get full member details
      const memberResponse = await axios.get(
        `${BASE_URL}/members/${req.member.id}`,
        {
          headers: { 'X-API-KEY': API_KEY }
        }
      );

      const member = memberResponse.data.data;

      // A member that no longer exists comes back as { data: null }
      if (!member) {
        return res.status(401).json({ error: 'Authentication required' });
      }

      // Check if member has the required plan (ACTIVE and TRIALING both grant access)
      const hasPlan = member.planConnections.some(
        plan =>
          plan.planId === requiredPlanId &&
          ['ACTIVE', 'TRIALING'].includes(plan.status)
      );

      if (!hasPlan) {
        return res.status(403).json({ error: 'Access denied. Required plan not found.' });
      }

      // Member has the required plan, proceed
      next();
    } catch (error) {
      console.error('Plan verification error:', error.message);
      return res.status(500).json({ error: 'Error verifying access' });
    }
  };
}

module.exports = { requirePlan };

// Usage example
// routes/premium-api.js
const express = require('express');
const router = express.Router();
const { requireAuth } = require('../middleware/auth');
const { requirePlan } = require('../middleware/rbac');

// Protected premium route
router.get(
  '/premium-content',
  requireAuth,
  requirePlan('pln_premium'),
  (req, res) => {
    res.json({
      message: 'This is premium content',
      content: 'Your exclusive premium data here'
    });
  }
);

module.exports = router;
Need help?
Can't find what you're looking for? Our team is here to help.