<!-- Source: https://developers.memberstack.com/admin-rest-api/edge-functions -->
<!-- Markdown version of a Memberstack developer documentation page. Canonical HTML: https://developers.memberstack.com/admin-rest-api/edge-functions -->

# Edge Functions (Supabase, Cloudflare Workers, Deno)

Authenticate Memberstack members and check their plan from a Supabase Edge Function, a Cloudflare Worker or any other Deno or edge runtime. Your frontend sends the member’s token, and your function verifies it before it returns anything private.

Before You Start

-   Your App ID: in the dashboard, open **Developer → Keys & IDs** and copy it from the **Application ID** card. It looks like `app_your_app_id`.
-   Your secret key: same page, **API keys** card, **Secret key** field. Keys are per mode, and Test Mode keys start with `sk_sb_`. The secret key is server-side only: store it as a function secret and never put it in frontend code.
-   A frontend that logs members in with the Memberstack script tag or `@memberstack/dom`.

## How It Works

1.  The member logs in on your site. Memberstack stores their token, a signed JWT, in the browser.
2.  Your frontend reads the token and sends it to your function in an `Authorization: Bearer <token>` header.
3.  Your function verifies the token with one of the three methods below. A valid token gives you the member ID (the `id` claim).
4.  If the endpoint is for paying members, your function fetches the member with the Admin REST API and checks their plan connections.

Only trust the member ID that comes out of a verified token. Never trust a member ID or plan ID that the browser sends in the request body.

## Send the Token From Your Frontend

`getMemberCookie()` returns the logged-in member’s token as a string, or `undefined` when nobody is logged in. Despite the name, it works with or without `useCookies`: it checks `localStorage` first, then the `_ms-mid` cookie.

**@memberstack/dom**

```js
import memberstackDOM from "@memberstack/dom";

const memberstack = memberstackDOM.init({ publicKey: "pk_sb_your_public_key" });

export async function callMemberFunction() {
  const token = memberstack.getMemberCookie();
  if (!token) throw new Error("Not logged in");

  const res = await fetch("https://your-function-url/member-check", {
    headers: { Authorization: `Bearer ${token}` },
  });
  return res.json();
}
```

**Script tag**

```html
<script data-memberstack-app="app_your_app_id" src="https://static.memberstack.com/scripts/v2/memberstack.js" type="text/javascript"></script>
<script>
  async function callMemberFunction() {
    // The hosted script exposes the @memberstack/dom methods on window.$memberstackDom
    const token = window.$memberstackDom.getMemberCookie();
    if (!token) return; // not logged in

    const res = await fetch("https://your-function-url/member-check", {
      headers: { Authorization: "Bearer " + token },
    });
    console.log(await res.json());
  }

  if (window.$memberstackReady) callMemberFunction();
  else document.addEventListener("memberstack.ready", callMemberFunction);
</script>
```

**supabase-js**

```js
import memberstackDOM from "@memberstack/dom";
import { createClient } from "@supabase/supabase-js";

const memberstack = memberstackDOM.init({ publicKey: "pk_sb_your_public_key" });
const supabase = createClient("YOUR_SUPABASE_URL", "YOUR_SUPABASE_PUBLISHABLE_KEY");

const token = memberstack.getMemberCookie();
if (!token) throw new Error("Not logged in");

const { data, error } = await supabase.functions.invoke("member-check", {
  headers: { Authorization: `Bearer ${token}` },
});
```

With supabase-js, an `Authorization` header passed to `functions.invoke()` takes priority, so it replaces the Supabase session token for that call. supabase-js only adds its own `Authorization` header when you haven’t set one.

Why not read the \_ms-mid cookie in the function?

By default `@memberstack/dom` and the script tag keep the token in `localStorage` and write no cookie. With `useCookies` on, the `_ms-mid` cookie is `SameSite=Strict` and scoped to your site’s host (or its root domain, with `setCookieOnRootDomain` on a matching custom domain), so the browser never sends it to a function on `*.supabase.co` or `*.workers.dev`. Send the token in the `Authorization` header instead.

## Choose a Verification Method

| Method | Network per request | What it checks | Runs on |
| --- | --- | --- | --- |
| [A: REST `POST /members/verify-token`](#option-a-verify-token-endpoint) | One call to `admin.memberstack.com`. Rate limited to 25 requests per second per IP (on Cloudflare Workers, that IP may be shared: see [Cloudflare Workers](#cloudflare-workers)). | Signature, issuer, audience (the app that owns your secret key), expiry, and the member’s session version. | Any runtime with `fetch`. |
| [B: `@memberstack/admin` `verifyToken`](#option-b-admin-package) | No call to Memberstack per request. Public keys are fetched on first use and cached (10 minutes by default). | Signature, issuer, expiry. Audience only when you pass `audience`. | Node, Deno (`npm:`), Supabase Edge Runtime, Cloudflare Workers with `nodejs_compat`. |
| [C: `jose` + JWKS URL](#option-c-jose) | No call to Memberstack per request. Public keys are fetched on first use and cached. | Signature, plus the issuer, audience and expiry you configure. | Deno and Supabase Edge Runtime (tested). |

The REST endpoint also compares the token’s `sv` (session version) claim with the member’s current session version, so it rejects tokens from sessions Memberstack has ended. Local verification (B and C) can’t see that. Today that happens in one rare case: an unverified account taken over by a social login that proves the email address. For most apps, all three methods accept the same tokens. None of them can detect a logout (see [Logout and Token Lifetime](#logout-and-token-lifetime)).

Always check the audience

Member tokens for every Memberstack app are signed with the same key and carry the same issuer, `https://api.memberstack.com`. The `aud` claim is the only thing that ties a token to your app. The REST endpoint checks it for you. With `verifyToken` or `jose`, always pass your App ID as `audience`: without it, a valid token issued for a different app also verifies.

Neither library complains when the value is missing: `verifyToken` skips the audience check when `audience` is `undefined` or an empty string, and `jose` when it is `undefined`. That is what you get from an unset environment variable, so the samples below stop with an error when `MEMBERSTACK_APP_ID` isn’t set.

## Option A: The verify-token Endpoint

Send the token to `POST https://admin.memberstack.com/members/verify-token` with your secret key in the `X-API-Key` header. This only needs `fetch`, so the same function works in Supabase Edge Functions, Cloudflare Workers and Deno.

verify-member.ts Copy

```ts
export type MemberToken = {
  id: string; // member ID, mem_...
  type: "member";
  iat: number;
  exp: number;
  aud: string; // your App ID
  iss: string; // "https://api.memberstack.com"
  sv?: number; // session version, present only after Memberstack has ended this member's sessions
};

// Returns the decoded token, or null if the token is not valid.
// Throws if the request itself failed (wrong secret key, rate limit, network).
export async function verifyMemberToken(token: string, secretKey: string): Promise<MemberToken | null> {
  const res = await fetch("https://admin.memberstack.com/members/verify-token", {
    method: "POST",
    headers: { "X-API-Key": secretKey, "Content-Type": "application/json" },
    body: JSON.stringify({ token }),
  });

  if (res.ok) {
    const { data } = await res.json();
    return data;
  }

  // 400 { code: "INVALID_TOKEN" }: missing, malformed, tampered, expired, or another app's token
  if (res.status === 400) {
    const body = await res.json().catch(() => null);
    if (body?.code === "INVALID_TOKEN") return null;
  }

  // 400/401 "validation/invalid-secret-key", or 429 (text body, not JSON)
  throw new Error(`Memberstack verify-token failed: HTTP ${res.status}`);
}
```

**200 OK**

```json
{
  "data": {
    "id": "mem_abc123",
    "type": "member",
    "iat": 1763078400,
    "exp": 1764288000,
    "aud": "app_your_app_id",
    "iss": "https://api.memberstack.com"
  }
}
```

**400 Invalid token**

```json
{ "code": "INVALID_TOKEN", "message": "Invalid token" }
```

**400/401 Bad secret key**

```json
{ "code": "validation/invalid-secret-key", "message": "The provided secret key is invalid." }
```

-   **What it checks**: the token’s `kid` header matches a Memberstack signing key; the RS256 signature, `iss` (`https://api.memberstack.com`), `aud` (the App ID that owns your secret key) and `exp` (in the future) all pass; then the token’s `sv` claim (0 when absent) matches the member’s current session version. Any failure returns `400` with `"code": "INVALID_TOKEN"`.
-   **What it returns**: the decoded token claims only, not the member. To check plans, fetch the member separately ([Check Plan Access](#check-plan-access)).
-   **Key errors**: a missing secret key, or one that doesn’t start with `sk`, returns `400`. An unknown `sk_` key returns `401`. Both use `"code": "validation/invalid-secret-key"`. These are problems with your request, not the member’s token, so don’t treat them as a failed login.
-   **Rate limit**: the Admin REST API allows 25 requests per second per IP address, not per key. Requests with a bad or missing key count too. Over the limit, you get `429` with a text body (not JSON, served as `text/html`), `Too many requests, please try again later.`, and a `Retry-After` header in seconds. Every response carries `RateLimit-Policy`, `RateLimit-Limit`, `RateLimit-Remaining` and `RateLimit-Reset` headers. If your function handles a lot of traffic, or runs on Cloudflare Workers (see [Cloudflare Workers](#cloudflare-workers)), verify locally (Option B or C).

## Option B: @memberstack/admin

`@memberstack/admin` 1.8.0 verifies tokens locally against Memberstack’s public keys at `https://auth.memberstack.com/.well-known/member-jwks.json`. Versions before 1.8.0 fetched the keys from an S3 file over plain HTTP, so use 1.8.0 or later. In Deno and Supabase, import it with an `npm:` specifier.

**Deno / Supabase**

```ts
import memberstackAdmin from "npm:@memberstack/admin@1.8.0";

const memberstack = memberstackAdmin.init(Deno.env.get("MEMBERSTACK_SECRET_KEY")!);

// Fail fast: verifyToken skips the audience check when audience is undefined or "".
const APP_ID = Deno.env.get("MEMBERSTACK_APP_ID") ?? "";
if (!APP_ID) throw new Error("MEMBERSTACK_APP_ID is not set");

// jose error codes that mean the public keys couldn't be loaded. A rejection
// without a jose code (one starting "ERR_J"), such as a network error, means the same.
const KEY_ERRORS = ["ERR_JWKS_TIMEOUT", "ERR_JWKS_INVALID", "ERR_JOSE_GENERIC"];
export function isKeyError(err: unknown): boolean {
  const code = (err as { code?: unknown } | null)?.code;
  return typeof code !== "string" || !code.startsWith("ERR_J") || KEY_ERRORS.includes(code);
}

// Returns the decoded token, or null if it is not valid.
// Throws if the public keys couldn't be loaded (answer 503, not 401).
export async function verifyMemberToken(token: string) {
  try {
    // Always pass audience. Without it, a valid token from any Memberstack app passes.
    return await memberstack.verifyToken({ token, audience: APP_ID });
  } catch (err) {
    if (isKeyError(err)) throw err;
    return null; // expired, tampered, wrong app, or not a JWT
  }
}
```

**Cloudflare Workers**

```js
import memberstackAdmin from "@memberstack/admin";

// jose error codes that mean the public keys couldn't be loaded. A rejection
// without a jose code (one starting "ERR_J"), such as a network error, means the same.
const KEY_ERRORS = ["ERR_JWKS_TIMEOUT", "ERR_JWKS_INVALID", "ERR_JOSE_GENERIC"];
export function isKeyError(err) {
  const code = err?.code;
  return typeof code !== "string" || !code.startsWith("ERR_J") || KEY_ERRORS.includes(code);
}

// Workers pass secrets in `env`, so create the client inside fetch().
// The public keys are cached at module level and shared across init() clients.
export async function verifyMemberToken(token, env) {
  // Fail fast: verifyToken skips the audience check when audience is undefined or "".
  if (!env.MEMBERSTACK_APP_ID) throw new Error("MEMBERSTACK_APP_ID is not set");

  const memberstack = memberstackAdmin.init(env.MEMBERSTACK_SECRET_KEY);
  try {
    return await memberstack.verifyToken({ token, audience: env.MEMBERSTACK_APP_ID });
  } catch (err) {
    if (isKeyError(err)) throw err; // keys couldn't be loaded: answer 503
    return null;
  }
}
```

-   **Return value**: the decoded token, `{ id, type, iat, exp, aud, iss }` (plus `sv` for a member whose sessions Memberstack has ended before). The TypeScript type `VerifiedMemberToken` only declares `id`, `type`, `iat` and `exp`, but `aud` and `iss` are there at runtime.
-   **Errors**: `verifyToken` rejects on any failure with a `jose` error that has a `.code`, for example `ERR_JWT_EXPIRED`, `ERR_JWT_CLAIM_VALIDATION_FAILED` (wrong audience or issuer), `ERR_JWS_SIGNATURE_VERIFICATION_FAILED` or `ERR_JWS_INVALID` (not a JWT). Treat those as unauthenticated. The exception is a failure to load the public keys: `ERR_JWKS_TIMEOUT`, `ERR_JWKS_INVALID`, `ERR_JOSE_GENERIC` (the key download didn’t return a valid key set), or an error with no `jose` code, such as a network error. That says nothing about the token, so answer `503` rather than `401`, or every member looks logged out while the keys are unreachable. The `isKeyError` helper above sorts the two.
-   **Key caching**: the package creates one key set per process and fetches the public keys once. By default it re-fetches after 10 minutes and gives up on a key fetch after 5 seconds (`ERR_JWKS_TIMEOUT`).
-   **Deno**: run with `--allow-net --allow-env`. `--allow-env` is required even if your code never reads environment variables: without it the import itself fails with `NotCapable: Requires env access`, thrown by a dependency of `axios`. Tested with Deno 2.9.6.
-   **Supabase Edge Functions**: Supabase recommends `npm:` specifiers for npm packages. `verifyToken` and `members.retrieve` were run in Supabase’s Edge Runtime (Docker image `supabase/edge-runtime:v1.79.3`) locally, not on a hosted project.
-   **Cloudflare Workers**: install with `npm install @memberstack/admin`, then add `compatibility_flags = ["nodejs_compat"]` to your Wrangler config, or use a `compatibility_date` of `2026-08-04` or later. Without either, the build fails with `Could not resolve "crypto"`, because the package loads Node’s `crypto` (for webhook signatures) when it’s imported. Tested with `wrangler dev` (Wrangler 4.166.0, local workerd), not on a deployed Worker.

## Option C: jose and the JWKS URL

If you don’t want the Admin package, verify the token with [jose](https://github.com/panva/jose) against the public key set. Verifying this way needs no secret key. You still need the secret key to fetch the member for a plan check.

Deno / Supabase Copy

```ts
import { createRemoteJWKSet, jwtVerify } from "npm:jose@6";

// Fail fast: jose skips the audience check when audience is undefined.
const APP_ID = Deno.env.get("MEMBERSTACK_APP_ID") ?? "";
if (!APP_ID) throw new Error("MEMBERSTACK_APP_ID is not set");

// Create the key set once, at module scope, so keys are cached between requests.
const JWKS = createRemoteJWKSet(
  new URL("https://auth.memberstack.com/.well-known/member-jwks.json"),
);

// jose error codes that mean the public keys couldn't be loaded. A rejection
// without a jose code (one starting "ERR_J"), such as a network error, means the same.
const KEY_ERRORS = ["ERR_JWKS_TIMEOUT", "ERR_JWKS_INVALID", "ERR_JOSE_GENERIC"];
export function isKeyError(err: unknown): boolean {
  const code = (err as { code?: unknown } | null)?.code;
  return typeof code !== "string" || !code.startsWith("ERR_J") || KEY_ERRORS.includes(code);
}

// Returns the decoded token (payload.id is the member ID), or null if it is not valid.
// Throws if the public keys couldn't be loaded (answer 503, not 401).
export async function verifyMemberToken(token: string) {
  try {
    const { payload } = await jwtVerify(token, JWKS, {
      issuer: "https://api.memberstack.com",
      audience: APP_ID,
      algorithms: ["RS256"],
      requiredClaims: ["exp"],
    });
    if (payload.type !== "member") return null;
    return payload;
  } catch (err) {
    if (isKeyError(err)) throw err;
    return null;
  }
}
```

-   Member tokens are RS256 JWTs with a `kid` header. The claims are `id` (the member ID, `mem_…`), `type: "member"`, `iat`, `exp`, `aud` (your App ID) and `iss` (`https://api.memberstack.com`), plus `sv` (session version) for a member whose sessions Memberstack has ended before. A token from the dashboard’s **Login as member** button also carries `isAdmin: true` (and expires after an hour). There is no plan data.
-   The sample pins `algorithms: ["RS256"]` and rejects any token whose `type` isn’t `"member"`, the same checks as [Verifying Without the Admin Package](/admin-node-package/verification#verify-without-the-admin-package).
-   The JWKS URL answers with `Cache-Control: public, max-age=600` and `Access-Control-Allow-Origin: *`.
-   A wrong `audience` or `issuer` fails with `ERR_JWT_CLAIM_VALIDATION_FAILED`.
-   This code was run in Deno 2.9.6 (with `--allow-net=auth.memberstack.com`, plus `--allow-env` to read environment variables) and in Supabase’s Edge Runtime locally. On Cloudflare Workers, the tested path is Option B.

## Check Plan Access

A token carries the member ID but no plan information. To check plans, fetch the member with `GET https://admin.memberstack.com/members/:id` using the ID from the verified token, then look at `planConnections`. A plan grants access when its connection’s `status` is `ACTIVE` or `TRIALING`, which is the same rule Memberstack uses for gated content.

**fetch (any runtime)**

```ts
const ACCESS_STATUSES = ["ACTIVE", "TRIALING"];

export async function hasPlan(memberId: string, planId: string, secretKey: string): Promise<boolean> {
  const res = await fetch(
    `https://admin.memberstack.com/members/${encodeURIComponent(memberId)}`,
    { headers: { "X-API-Key": secretKey } },
  );
  if (!res.ok) throw new Error(`Memberstack member lookup failed: HTTP ${res.status}`);

  // An unknown or deleted member returns 200 { "data": null }, not 404.
  const { data: member } = await res.json();
  if (!member) return false;

  return member.planConnections.some(
    (pc: { planId: string; status: string }) =>
      pc.planId === planId && ACCESS_STATUSES.includes(pc.status),
  );
}
```

**@memberstack/admin**

```ts
import memberstackAdmin from "npm:@memberstack/admin@1.8.0"; // "@memberstack/admin" on Workers/Node

const memberstack = memberstackAdmin.init(Deno.env.get("MEMBERSTACK_SECRET_KEY")!);

export async function hasPlan(memberId: string, planId: string): Promise<boolean> {
  // Resolves { data: null } for an unknown member (it does not throw).
  const { data: member } = await memberstack.members.retrieve({ id: memberId });
  if (!member) return false;

  return member.planConnections.some(
    (pc) =>
      typeof pc === "object" && // the type allows strings; at runtime these are objects
      pc.planId === planId &&
      (pc.status === "ACTIVE" || pc.status === "TRIALING"),
  );
}
```

| status | Access | When you see it |
| --- | --- | --- |
| ACTIVE | Yes | Paid, free or one-time plan in good standing. A subscription set to cancel at period end stays `ACTIVE` (with `payment.cancelAtDate` set) until the period ends. |
| TRIALING | Yes | Stripe subscription in its trial period. |
| REQUIRES\_PAYMENT | No | Stripe subscription `past_due` or `unpaid`. |
| REQUIRES\_AUTHENTICATION | No | Stripe subscription `incomplete`. |
| CANCELED | No | Subscription ended (`canceled` or `incomplete_expired`). |

Don’t gate on the active field

Each plan connection also has an `active` boolean, and it is not the same as access. In the Admin REST API, `active` reflects the latest payment, not the subscription status. In `@memberstack/dom`, `active` is `status === "ACTIVE"`, so a trialing member shows `active: false` even though they have access. Check `status` for `ACTIVE` or `TRIALING` instead.

Plans the member uses as a team seat are included in `planConnections` with `payment: null`, so the same check covers team members. Each lookup is another Admin REST request and counts toward the 25 requests per second limit.

## Supabase Edge Functions

### Turn off Supabase’s JWT check for this function

Supabase’s `verify_jwt` setting is on by default. When it’s on, Supabase’s gateway inspects the `Authorization` header and, if it is missing, malformed or signed with a different key, returns `401` before your code runs. A Memberstack token is signed by Memberstack, not by your Supabase project, so it falls into that last case. Turn `verify_jwt` off for this function and do the Memberstack check in your code.

**supabase/config.toml**

```toml
[functions.member-check]
verify_jwt = false
```

**CLI flag**

```bash
supabase functions deploy member-check --no-verify-jwt

# Local development: start the local stack first, then serve
# (serves every function in the project, all with the JWT check off)
supabase start
supabase functions serve --no-verify-jwt
```

`supabase functions new member-check` already adds a `[functions.member-check]` table to `config.toml` (Supabase CLI 3.3.0 writes `verify_jwt = false` there). Set `verify_jwt = false` in that table instead of pasting a second one: a duplicate table makes every CLI command fail with `trying to redefine an already defined table or value`. In a local test, `supabase functions serve --no-verify-jwt` turned the check off even with `verify_jwt = true` in `config.toml`.

Your function is now public

With `verify_jwt` off, every request reaches your code, including requests with no token at all. Your function must reject any request without a valid Memberstack token, as in the example below.

The gateway behaviour described here comes from Supabase’s documentation. The function code on this page was run in Supabase’s Edge Runtime locally, not through a hosted Supabase project’s gateway.

### Store your keys as secrets

Terminal Copy

```bash
supabase secrets set MEMBERSTACK_SECRET_KEY=sk_sb_your_secret_key
supabase secrets set MEMBERSTACK_APP_ID=app_your_app_id
```

Read them with `Deno.env.get("MEMBERSTACK_SECRET_KEY")`. Functions pick up a new secret immediately, without a redeploy. Secret names can’t start with `SUPABASE_`.

`supabase secrets set` only sets them on your hosted project. For local development with `supabase functions serve` (run `supabase start` first; `serve` needs the local stack), put the same names in `supabase/functions/.env` (don’t commit it), or pass another file with `--env-file`.

### Complete function

This function handles the CORS preflight, verifies the token with `@memberstack/admin` and checks one plan. It uses Supabase’s `corsHeaders` helper, available from `@supabase/supabase-js` 2.95.0.

index.ts Copy

```ts
import memberstackAdmin from "npm:@memberstack/admin@1.8.0";
import { corsHeaders } from "npm:@supabase/supabase-js@^2/cors";

const memberstack = memberstackAdmin.init(Deno.env.get("MEMBERSTACK_SECRET_KEY")!);
const PLAN_ID = "pln_your_plan_id";

// Fail fast: verifyToken skips the audience check when audience is undefined or "".
const APP_ID = Deno.env.get("MEMBERSTACK_APP_ID") ?? "";
if (!APP_ID) throw new Error("MEMBERSTACK_APP_ID is not set");

// jose error codes that mean the public keys couldn't be loaded. A rejection
// without a jose code (one starting "ERR_J"), such as a network error, means the same.
const KEY_ERRORS = ["ERR_JWKS_TIMEOUT", "ERR_JWKS_INVALID", "ERR_JOSE_GENERIC"];
function isKeyError(err: unknown): boolean {
  const code = (err as { code?: unknown } | null)?.code;
  return typeof code !== "string" || !code.startsWith("ERR_J") || KEY_ERRORS.includes(code);
}

function json(body: unknown, status = 200) {
  return Response.json(body, { status, headers: corsHeaders });
}

Deno.serve(async (req) => {
  // CORS preflight
  if (req.method === "OPTIONS") {
    return Response.json({ ok: true }, { headers: corsHeaders });
  }

  // 1. Read the Memberstack token from the Authorization header
  const token = (req.headers.get("Authorization") ?? "").replace(/^Bearer\s+/i, "");
  if (!token) return json({ error: "Not logged in" }, 401);

  // 2. Verify it. Always pass your App ID as the audience.
  let memberId: string;
  try {
    const payload = await memberstack.verifyToken({ token, audience: APP_ID });
    memberId = payload.id;
  } catch (err) {
    if (isKeyError(err)) return json({ error: "Try again later" }, 503);
    return json({ error: "Invalid or expired token" }, 401);
  }

  // 3. Load the member and check the plan
  let member;
  try {
    ({ data: member } = await memberstack.members.retrieve({ id: memberId }));
  } catch {
    return json({ error: "Could not load member" }, 502);
  }
  if (!member) return json({ error: "Member not found" }, 401);

  const hasPlan = member.planConnections.some(
    (pc) =>
      typeof pc === "object" &&
      pc.planId === PLAN_ID &&
      (pc.status === "ACTIVE" || pc.status === "TRIALING"),
  );
  if (!hasPlan) return json({ error: "Plan required" }, 403);

  return json({ memberId, message: "Members-only data" });
});
```

Call it from your site with ``supabase.functions.invoke("member-check", { headers: { Authorization: `Bearer ${token}` } })``, as shown in [Send the Token From Your Frontend](#send-the-token). To use Option A or C instead, swap step 2 for that option’s `verifyMemberToken`.

## Cloudflare Workers

**wrangler.toml**

```toml
name = "member-check"
main = "src/index.js"
compatibility_date = "2026-11-01"
compatibility_flags = ["nodejs_compat"]
```

**Secrets**

```bash
npm install @memberstack/admin

# Deployed Worker
npx wrangler secret put MEMBERSTACK_SECRET_KEY
npx wrangler secret put MEMBERSTACK_APP_ID

# Local "wrangler dev": put the same names in a .dev.vars file (don't commit it)
# MEMBERSTACK_SECRET_KEY=sk_sb_your_secret_key
# MEMBERSTACK_APP_ID=app_your_app_id
```

src/index.js Copy

```js
import memberstackAdmin from "@memberstack/admin";

const PLAN_ID = "pln_your_plan_id";

// jose error codes that mean the public keys couldn't be loaded. A rejection
// without a jose code (one starting "ERR_J"), such as a network error, means the same.
const KEY_ERRORS = ["ERR_JWKS_TIMEOUT", "ERR_JWKS_INVALID", "ERR_JOSE_GENERIC"];
function isKeyError(err) {
  const code = err?.code;
  return typeof code !== "string" || !code.startsWith("ERR_J") || KEY_ERRORS.includes(code);
}

// Standard CORS headers for a browser calling the Worker from your site
const CORS = {
  "Access-Control-Allow-Origin": "https://your-site.com",
  "Access-Control-Allow-Headers": "Authorization, Content-Type",
  "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
};

const json = (body, status = 200) => Response.json(body, { status, headers: CORS });

export default {
  async fetch(request, env) {
    if (request.method === "OPTIONS") {
      return new Response(null, { status: 204, headers: CORS });
    }

    // verifyToken skips the audience check when audience is undefined or "".
    if (!env.MEMBERSTACK_APP_ID) return json({ error: "Server misconfigured" }, 500);

    const token = (request.headers.get("Authorization") || "").replace(/^Bearer\s+/i, "");
    if (!token) return json({ error: "Not logged in" }, 401);

    const memberstack = memberstackAdmin.init(env.MEMBERSTACK_SECRET_KEY);

    let memberId;
    try {
      // Always pass your App ID as the audience
      const payload = await memberstack.verifyToken({ token, audience: env.MEMBERSTACK_APP_ID });
      memberId = payload.id;
    } catch (err) {
      if (isKeyError(err)) return json({ error: "Try again later" }, 503);
      return json({ error: "Invalid or expired token" }, 401);
    }

    let member;
    try {
      ({ data: member } = await memberstack.members.retrieve({ id: memberId }));
    } catch {
      return json({ error: "Could not load member" }, 502);
    }
    if (!member) return json({ error: "Member not found" }, 401);

    const hasPlan = member.planConnections.some(
      (pc) => pc.planId === PLAN_ID && (pc.status === "ACTIVE" || pc.status === "TRIALING"),
    );
    if (!hasPlan) return json({ error: "Plan required" }, 403);

    return json({ memberId, message: "Members-only data" });
  },
};
```

The CORS part is standard browser behaviour, not something Memberstack requires: a cross-origin request with an `Authorization` header triggers a preflight `OPTIONS` request, and the response must allow that header. Set `Access-Control-Allow-Origin` to your site’s origin.

Admin REST calls from a Worker may share a rate limit

The Admin REST API counts its 25 requests per second per client IP. `admin.memberstack.com` is served through Cloudflare, and Memberstack takes the client IP from Cloudflare’s `CF-Connecting-IP` header. Cloudflare’s documentation says that for a Worker subrequest to another Cloudflare zone, that header is set to one shared Worker address (`2a06:98c0:3600::103`), not your visitor’s IP. So Admin REST requests from your Worker may share a rate-limit bucket with other Workers calling the API, and get `429` for traffic that isn’t yours. This follows from Cloudflare’s documentation and Memberstack’s code; it hasn’t been observed from a deployed Worker.

To stay clear of it, verify tokens locally (Option B, as in the sample above, or Option C) rather than with the verify-token endpoint, and avoid a member lookup on every request where you can, for example by caching the plan check for a short time. When you do get a `429`, wait the number of seconds in `Retry-After` before you retry.

Need it on a runtime not covered here? Option A only needs `fetch`, so it runs anywhere, but mind the rate limit above. Option C needs `fetch` and Web Crypto. `@memberstack/admin` needs Node compatibility (`crypto` and `process.env`).

## Logout and Token Lifetime

-   **Tokens expire** after your app’s session length (`exp` is fixed when the token is issued at login or signup). The default is 14 days. Change it under **Authentication → Security → Session length**.
-   **Logout does not revoke a token that was already issued.** `logout()` removes the token from the browser, but any copy of it still passes the verify-token endpoint, `verifyToken` and `jose` until its `exp`.
-   **Plans aren’t in the token.** It carries the member ID, type, timestamps, audience and issuer, not plan data, so check plans with the Admin REST API on each request that needs them.

Next Steps

[

Verification

The verify-token endpoint in full

](/admin-rest-api/verification)[

Member Management

Retrieve, list, create and update members

](/admin-rest-api/member-actions)[

Admin Package Verification

verifyToken and webhook verification in Node.js

](/admin-node-package/verification)

Need help?

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

[Join the Slack community](https://www.memberstack.com/slack)[Find an expert](https://www.memberstack.com/experts)

[

Previous

Verification

](/admin-rest-api/verification)[

Next

Common Use Cases

](/admin-rest-api/common-use-cases)
