Next.js App Router
Build gated pages in a Next.js App Router app: log members in with @memberstack/dom in the browser, then verify their session cookie and check their plan on the server with @memberstack/admin.
- Tested with Next.js 16.4.6 and React 19.3.0, with Cache Components on (the
create-next-appdefault since 16.4),@memberstack/admin1.8.0 and@memberstack/dom2.1.1 - You need a Memberstack app with a plan and a price. Use your Test Mode keys while you build
- Every file path below is relative to your project root and uses the
@/import alias
How It Fits Together
- Browser.
@memberstack/domlogs the member in. Initialized withuseCookies: true, it stores the member’s token (a JWT) in a cookie named_ms-mid. WithoutuseCookies, the token goes tolocalStorageand your server never sees it. - Server. A server component or route handler reads
_ms-midwithcookies()and checks it withverifyToken()from@memberstack/admin. That confirms the signature, the issuer, the expiry and that the token belongs to your app. - Plans. The token carries the member ID but no plan data, so the server fetches the member with
members.retrieve()and checksplanConnections.
The SDK writes the cookie as _ms-mid=<JWT>; path=/; SameSite=Strict, plus Secure on https: pages. It isn’t HttpOnly, because browser JavaScript writes it. Its expiry is the session length rounded up to whole days, so the cookie can outlive the token by up to a day. A cookie that exists isn’t proof of a session: rely on verifyToken(), which rejects the token once its exp has passed.
Find Your Keys and App ID
In the Memberstack dashboard, open Developer → Keys & IDs:
- Application ID card: your App ID (
app_…). You pass it as theaudiencewhen you verify tokens. - API keys card: the Public key (
pk_…) for the browser, and the Secret key (sk_…) for the server only.
Keys are per mode. The page-header toggle shows Viewing: Test data or Viewing: Live data; in Test Mode the keys start with pk_sb_ and sk_sb_. Switch to Live Mode and copy the live keys before you deploy. The App ID is the same in both modes.
For the plan and price IDs, open Plans and select your plan. Its More actions menu (⋮) has Copy plan ID (pln_…). Each price card shows a shortened prc_… ID; click it to copy the full price ID.
Create the app and install the packages. --yes accepts the defaults: TypeScript, the App Router, no src/ directory, the @/* import alias and Cache Components on.
npx create-next-app@16.4.6 my-app --yes
cd my-app
npm install @memberstack/dom @memberstack/admin server-only# .env.local
# Sent to the browser (Next.js inlines NEXT_PUBLIC_ variables into client code)
NEXT_PUBLIC_MEMBERSTACK_PUBLIC_KEY=pk_sb_your_public_key
NEXT_PUBLIC_MEMBERSTACK_PRICE_ID=prc_your_price_id
# Server only. Never prefix these with NEXT_PUBLIC_
MEMBERSTACK_SECRET_KEY=sk_sb_your_secret_key
MEMBERSTACK_APP_ID=app_your_app_id
MEMBERSTACK_PLAN_ID=pln_your_plan_idOnly the public key and price ID belong in NEXT_PUBLIC_ variables. The secret key gives full admin access to your app; read it only in server code such as lib/memberstack.ts, which imports server-only.
Initialize the DOM Package
Create one browser-only instance. useCookies: true is the setting that makes server-side checks possible.
"use client";
import memberstackDOM from "@memberstack/dom";
type Memberstack = ReturnType<typeof memberstackDOM.init>;
let instance: Memberstack | null = null;
// Browser only. useCookies: true stores the member token in the _ms-mid
// cookie (instead of localStorage), so your server can read it.
export function getMemberstack(): Memberstack {
if (typeof window === "undefined") {
throw new Error("getMemberstack() only runs in the browser");
}
if (!instance) {
instance = memberstackDOM.init({
publicKey: process.env.NEXT_PUBLIC_MEMBERSTACK_PUBLIC_KEY!,
useCookies: true,
});
}
return instance;
}Log members in
The DOM package stores the token and returns, but never navigates. After login, do a full page load so the next server request carries the new cookie and every server component, shared layouts included, renders again. Signup works the same way with signupMemberEmailPassword(). If the member is already signed in, the form also shows a link on to /dashboard (see the first request after checkout for why a signed-in member can land on /login).
"use client";
import { useEffect, useState, type FormEvent } from "react";
import { getMemberstack } from "@/lib/memberstack-client";
export default function LoginForm() {
const [error, setError] = useState<string | null>(null);
const [signedIn, setSignedIn] = useState(false);
// Already signed in? Offer the way on; a plain <a> gives a full page load.
// A link from an email or another site can land here because its first
// request had no SameSite=Strict cookie. Don't redirect automatically: if
// the server can't verify the token (wrong MEMBERSTACK_APP_ID, no cookie
// yet), that would bounce between /login and /dashboard forever.
useEffect(() => {
getMemberstack()
.getCurrentMember()
.then(({ data }) => setSignedIn(Boolean(data)))
.catch(() => {}); // expired or invalid token: just show the form
}, []);
async function onSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
const form = new FormData(event.currentTarget);
setError(null);
try {
await getMemberstack().loginMemberEmailPassword({
email: String(form.get("email")),
password: String(form.get("password")),
});
// The SDK doesn't navigate. Use a full page load, not router.push(), so
// the server renders everything again (shared layouts too) with the new
// cookie.
window.location.assign(new URL("/dashboard", window.location.origin));
} catch (err) {
setError((err as { message?: string })?.message ?? "Login failed");
}
}
return (
<form onSubmit={onSubmit}>
<input name="email" type="email" required placeholder="Email" />
<input name="password" type="password" required placeholder="Password" />
<button type="submit">Log in</button>
{error && <p role="alert">{error}</p>}
{signedIn && (
<p>
You’re already signed in. <a href="/dashboard">Continue to your dashboard</a>
</p>
)}
</form>
);
}import LoginForm from "@/components/LoginForm";
export default function LoginPage() {
return (
<main>
<h1>Log in</h1>
<LoginForm />
</main>
);
}Read the Member on the Server
Put the session check in one server-only module, as the Next.js authentication guide recommends (a “Data Access Layer”). React’s cache() means several components can call getMember() in one request and only one check runs.
import "server-only";
import memberstackAdmin from "@memberstack/admin";
import { cookies } from "next/headers";
import { connection } from "next/server";
import { cache } from "react";
const memberstack = memberstackAdmin.init(process.env.MEMBERSTACK_SECRET_KEY!);
// Returns the signed-in member, or null. cache() dedupes calls within one request.
export const getMember = cache(async () => {
const appId = process.env.MEMBERSTACK_APP_ID;
// Without an audience, verifyToken skips the aud check entirely.
if (!appId) throw new Error("MEMBERSTACK_APP_ID is not set");
const token = (await cookies()).get("_ms-mid")?.value;
if (!token) return null;
await connection(); // jose reads the clock (token expiry, key cache)
let memberId: string;
try {
({ id: memberId } = await memberstack.verifyToken({ token, audience: appId }));
} catch {
return null; // expired, tampered, wrong app, or not a JWT
}
// The token has no plan data. Fetch the member with the secret key.
const { data } = await memberstack.members.retrieve({ id: memberId });
return data ?? null; // { data: null } when the member no longer exists
});
export type Member = NonNullable<Awaited<ReturnType<typeof getMember>>>;
// Same rule Memberstack uses for gated content: ACTIVE or TRIALING.
export function hasActivePlan(member: Member, planId: string): boolean {
return member.planConnections.some(
(pc) =>
typeof pc === "object" &&
pc.planId === planId &&
(pc.status === "ACTIVE" || pc.status === "TRIALING"),
);
}Always pass audience
verifyToken({ token, audience }) checks the token’s signature against Memberstack’s public keys, that the issuer is https://api.memberstack.com, that exp is in the future, and, only when audience is set, that the token’s aud claim equals your App ID. If audience is missing or empty, that last check is skipped, so a valid token issued for a different Memberstack app would pass. The helper throws if MEMBERSTACK_APP_ID isn’t set rather than verify without it.
On success it resolves the decoded token: id (the member ID, mem_…), type: "member", iat, exp, aud and iss, 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. On any failure it rejects, and the helper treats every rejection as “not signed in”. That includes a failure to fetch Memberstack’s public keys (ERR_JWKS_TIMEOUT or a network error), so during an outage signed-in members look signed out; log the error in the catch if you need to tell the two apart.
Cache Components rules
Apps created with create-next-app 16.4 or later have Cache Components on (cacheComponents: true in next.config.ts). If yours does, three things follow:
- Call
await connection()beforeverifyToken(). Without it, pages still verify correctly, but Next.js logsNext.js encountered the unstable value `Date.now()` while prerenderingon every request after the first. The token library reads the clock when it checks expiry and its cached keys.await cookies()alone doesn’t prevent this. - Wrap the component that calls
getMember()in<Suspense>. Reading cookies outside a Suspense boundary failsnext buildwithNext.js encountered uncached or runtime data during prerendering. With the boundary, the page builds as a partial prerender: the static shell is prerendered and the member part streams in per request. - Don’t add
export const dynamic = "force-dynamic". Under Cache Components it fails the build withRoute segment config "dynamic" is not compatible with `nextConfig.cacheComponents`. Please remove it.
Check Plan Access
hasActivePlan() in the helper above grants access when the member has a connection to the plan whose status is ACTIVE or TRIALING. That is the same rule Memberstack applies to gated content and plan permissions. The other statuses, REQUIRES_PAYMENT (Stripe past_due or unpaid), REQUIRES_AUTHENTICATION and CANCELED, deny access.
Each plan connection also has an active boolean, but it doesn’t mean “has access”. In the Admin API it reflects the latest payment, not the subscription status; in the browser SDK it is false for trialing members. Check status instead.
Two typing quirks in @memberstack/admin 1.8.0 that the helper handles:
planConnectionsis typed(string | { id; active; status; planId; … })[]. At runtime every entry is an object, but TypeScript needstypeof pc === "object"before you readpc.planId.statusis typed asstring.members.retrieve()resolves{ data: null }when no member matches (it doesn’t reject), butdatais typed as non-null. Keep the null check.
A subscription set to cancel at the end of the period stays ACTIVE until Stripe ends it, then becomes CANCELED. Plans a member uses as a team seat are included in planConnections with payment: null.
Protect Pages and Routes
Server component
The gated page keeps a static shell and does the member check inside <Suspense>. Members without the plan see an upgrade button; visitors who aren’t signed in go to /login.
import { Suspense } from "react";
import { redirect } from "next/navigation";
import { getMember, hasActivePlan } from "@/lib/memberstack";
import UpgradeButton from "@/components/UpgradeButton";
import LogoutButton from "@/components/LogoutButton";
export default function DashboardPage() {
return (
<main>
<h1>Dashboard</h1>
<Suspense fallback={<p>Loading…</p>}>
<Dashboard />
</Suspense>
</main>
);
}
async function Dashboard() {
const member = await getMember();
if (!member) redirect("/login");
if (!hasActivePlan(member, process.env.MEMBERSTACK_PLAN_ID!)) {
return (
<>
<p>Signed in as {member.auth.email}. Upgrade to see this page.</p>
<UpgradeButton />
<LogoutButton />
</>
);
}
return (
<>
<p>Premium content for {member.auth.email}.</p>
<LogoutButton />
</>
);
}Because the shell has already streamed when redirect() runs, the response is a 200 and the redirect to /login happens in the browser. Add the optional proxy below if you want an HTTP 307 instead.
Route handler
Route handlers use the same helper. Return 401 when nobody is signed in and 403 when the plan is missing. Calls from your own pages with fetch("/api/premium") are same-origin, so the browser sends the cookie.
import { getMember, hasActivePlan } from "@/lib/memberstack";
export async function GET() {
const member = await getMember();
if (!member) {
return Response.json({ error: "Not signed in" }, { status: 401 });
}
if (!hasActivePlan(member, process.env.MEMBERSTACK_PLAN_ID!)) {
return Response.json({ error: "Plan required" }, { status: 403 });
}
return Response.json({ id: member.id, content: "premium data" });
}Proxy (optional)
In Next.js 16, middleware.ts is renamed proxy.ts and runs on Node.js. Next.js recommends Proxy only for optimistic checks, because it runs on every matched route, including prefetches. Use it to bounce visitors who have no cookie at all, and keep the real check in your server components and route handlers.
import { NextResponse, type NextRequest } from "next/server";
// Optimistic check only: is there a cookie at all? It does not verify it.
export function proxy(request: NextRequest) {
if (!request.cookies.has("_ms-mid")) {
return NextResponse.redirect(new URL("/login", request.url));
}
return NextResponse.next();
}
export const config = { matcher: ["/dashboard/:path*"] };Keep your checkout success page out of the matcher. The browser doesn’t send _ms-mid on the return from Stripe (see the next section), so a proxy guarding that page sends a paying member to /login.
Checkout and the Return From Stripe
Start checkout from a client component. The member must be logged in; otherwise the request fails with a 401 and code login-required.
"use client";
import { useState } from "react";
import { getMemberstack } from "@/lib/memberstack-client";
export default function UpgradeButton() {
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
async function upgrade() {
setError(null);
setBusy(true);
try {
// On success the SDK sends the browser to Stripe Checkout.
await getMemberstack().purchasePlansWithCheckout({
priceId: process.env.NEXT_PUBLIC_MEMBERSTACK_PRICE_ID!,
successUrl: "/checkout/success",
cancelUrl: "/",
});
} catch (err) {
// A 429 rejects with a plain string; other errors are { code, message }.
setError(
typeof err === "string"
? err
: ((err as { message?: string })?.message ?? "Checkout failed"),
);
setBusy(false);
}
}
return (
<div>
<button onClick={upgrade} disabled={busy}>
Upgrade
</button>
{error && <p role="alert">{error}</p>}
</div>
);
}How successUrl is handled
- Relative paths work from the SDK.
/checkout/successbecomeshttps://your-site.com/checkout/successbefore it’s sent. The API itself accepts only absolutehttp(s)URLs and rejects anything else with a 400. - Your query string is dropped. Everything after the first
?is removed, so don’t pass state in it. - Memberstack adds its own parameters. The member lands on
/checkout/success?forceRefetch=true&fromCheckout=true&msPriceId=prc_…&stripePriceId=….@memberstack/domdoesn’t read them. - Without
successUrl, a member who must still verify their email (when your app requires it) goes to the On Verification Required redirect. Otherwise the member goes to the On Signup / On Purchase redirect (from the plan, or Plans → Default settings → Redirects), else back to the page that started checkout. cancelUrldefaults to the current page. Its query string is dropped too.- Rate limit: one checkout request per 5 seconds per IP address. Over the limit, the promise rejects with the plain string
Too many requests, please try again later., not an object, which is why the button checkstypeof err === "string".
Memberstack creates the plan connection before it redirects the browser to your success URL, so the member already has the plan when that page loads.
The first request after checkout has no cookie
After payment, Stripe sends the browser to Memberstack, which redirects to your successUrl. That navigation started on Stripe’s site, and browsers send a SameSite=Strict cookie only on requests that start on your own site. So the first request for your success page arrives without _ms-mid, even though the member is logged in. If the success URL is a server-gated page, getMember() returns null and the paying member is sent to /login.
Fix: make the success page a client component that immediately navigates to the gated page. That second navigation starts on your site, so the cookie is sent and the server sees the new plan.
"use client";
import { useEffect } from "react";
// Stripe Checkout returns here. This request came from another site, so the
// browser left out the SameSite=Strict _ms-mid cookie. A navigation started
// by this page is same-site, so the next request includes it.
export default function CheckoutSuccessPage() {
useEffect(() => {
window.location.replace("/dashboard");
}, []);
return <p>Payment received. Loading your account…</p>;
}The same applies to cancelUrl (Stripe sends the browser straight there) and to any link into your site from another site, such as an email. Point cancelUrl at a public page, such as your home page /, and don’t assume a visitor without a cookie on that first request has no account. A cross-site link to /dashboard sends a signed-in member to /login: without the proxy through the page’s client-side redirect, with it through a 307. Either way the LoginForm reads the cookie in the browser and offers a link back to /dashboard.
Logout
"use client";
import { getMemberstack } from "@/lib/memberstack-client";
export default function LogoutButton() {
async function logout() {
const { data } = await getMemberstack().logout();
// data.redirect is your "On Logout" redirect from the dashboard.
window.location.href = data?.redirect ?? "/";
}
return <button onClick={logout}>Log out</button>;
}logout() calls Memberstack, and only when that request succeeds does it delete the _ms-mid cookie and the cached member in localStorage. If the request fails, for example on a network error, nothing is cleared locally. It doesn’t navigate; data.redirect is your On Logout redirect.
Logging out removes the cookie from that browser. It does not invalidate the token: a copy of it still passes verifyToken() until its exp, which is set by Authentication → Security → Session length (14 days by default). Don’t treat verifyToken() as a logout check.
Common Errors
The ERR_… errors below come from verifyToken(). The getMember() helper above turns them all into null, so to see them, log the error in its catch (catch (err) { console.error(err); return null; }).
| Error | Cause and fix |
|---|---|
/login says “You’re already signed in”, but the link comes back to /login | The server can’t read the member. Check that MEMBERSTACK_APP_ID matches Developer → Keys & IDs, and that the public and secret keys are from the same mode (both pk_sb_/sk_sb_, or both live): a Test Mode member isn’t found with a live secret key, so members.retrieve() returns { data: null }. A failure to fetch Memberstack’s public keys also makes getMember() return null; log the error in its catch to tell these apart. |
next build: Next.js encountered uncached or runtime data during prerendering … cookies() … accessed outside of <Suspense> | A component reads cookies outside a Suspense boundary. Wrap it in <Suspense>. |
next build: Route segment config "dynamic" is not compatible with `nextConfig.cacheComponents` | Remove export const dynamic. Use <Suspense> and connection() instead. |
Server log on every request after the first: Next.js encountered the unstable value `Date.now()` while prerendering | Add await connection() before verifyToken(). |
ERR_JWT_CLAIM_VALIDATION_FAILED: unexpected "aud" claim value | The token was issued for a different app. Check MEMBERSTACK_APP_ID against Developer → Keys & IDs. |
ERR_JWT_EXPIRED: "exp" claim timestamp check failed | The session ended. The member logs in again. |
ERR_JWS_SIGNATURE_VERIFICATION_FAILED: signature verification failed | The token was altered after it was issued. |
ERR_JWS_INVALID: Invalid Compact JWS | The cookie value isn’t a JWT. |
ERR_JWKS_NO_MATCHING_KEY or ERR_JWKS_TIMEOUT | The token’s key ID is unknown, or fetching Memberstack’s public keys took longer than 5 seconds. |
members.retrieve() rejects with { code: "validation/invalid-secret-key" } | MEMBERSTACK_SECRET_KEY is missing or wrong. The rejection is a plain object, not an Error. |
| Signed-in member looks signed out on the page right after checkout | The SameSite=Strict cookie isn’t sent on the return from Stripe. Use a client-side success page (see above). |
| Server never sees a member, even after login | The DOM package wasn’t initialized with useCookies: true, so the token is in localStorage. |
purchasePlansWithCheckout() rejects with Too many requests, please try again later. | More than one checkout request in 5 seconds from the same IP. Disable the button while a request is in flight. |
purchasePlansWithCheckout() rejects with code login-required | No member is logged in. Sign the visitor up or in first. |