@stripe/customer-portal
v0.0.2
Published
Embeddable customer authentication and billing components
Readme
@stripe/customer-portal
The package embeds a Metronome-powered customer billing portal in a React app. Metronome supplies plans, contracts, usage, credits, and balances; Stripe supplies customers, payment methods, payments, and issued invoices.
Link-powered authentication is the bundled sign-in layer.
authentication: "live" verifies real Link accounts. For a trusted preview,
authentication: "test" uses server-memory identities and the fixed 000000 code.
This option selects Link verification behavior, independently of billing environments.
Link authentication is optional. Use createBillingPortal on the server and
BillingProvider from /billing/react for existing application auth, including
Replit Auth. The host verifies its session and supplies a trusted Stripe customer
mapping. The bundled createCustomerPortal and CustomerPortalProvider remain
available when you choose Link sign-in. The billing-only APIs require version
0.0.2 or newer.
Private HTTP transport: Mount the Customer Portal server SDK at its same-origin base URL and let the client components communicate with it. All paths, methods, headers, request bodies, and response shapes beneath that mount are private implementation details and may change without notice. Use the public SDK exports; do not call internal endpoints directly.
Install
Install the package in your React app:
npm install @stripe/customer-portalSee the integration guide for route mounting and deployment setup. React and React DOM versions must satisfy the package peer dependencies.
Public entry points
| Entry point | Exports | | ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | | @stripe/customer-portal/server | createBillingPortal, createCustomerPortal, and their server option types | | @stripe/customer-portal/webmcp | createCustomerPortalWebMCP and its configuration, lifecycle, and status types | | @stripe/customer-portal/auth/react | CustomerPortalProvider, SignIn, SignedIn, SignedOut, UserButton, useUser, useAuth, and their props | | @stripe/customer-portal/billing/react | BillingProvider, CustomerPortal, Packages, Balance, TopUp, Usage, PaymentMethods, BillingHistory, BillingInformation, and their props | | @stripe/customer-portal/styles.css | Compiled component styles | | @stripe/customer-portal | The connected React exports above |
The server and browser entry points are separate. There is no public isomorphic runtime API. The internal provider clients, response models, UI primitives, and Storybook fixture views are not package exports.
Billing with existing application authentication
Use createBillingPortal with a server-only resolveSession callback. Verify the
host's cookie or bearer token, look up its user-to-Stripe-customer mapping in a
trusted store, and return { customerId, expiresAt }, or null when signed out.
customerId must be a cus_… ID and expiresAt the host session's ISO expiry.
The SDK verifies that customer with the configured Stripe account and key mode.
An expired session or deleted customer is signed out; verification/provider
failures deny access. Never resolve the customer from a browser ID or email alone.
Mount the handler on the same origin. It handles billing and signed webhooks and exposes the same customer/usage helpers. It does not create Link challenges, portal cookies, or sign-in/sign-out routes. The host owns session lifecycle and profile changes; the billing-only Profile view is read-only.
Render BillingProvider with stripePublishableKey, the current customerId,
and the usual appearance/base-path options. Mount it only after host sign-in and
unmount on sign-out. Cookies are sent on same-origin requests; supply getToken
if the host uses bearer tokens. Browser customerId binds requests and resets
state when identities change; it never authorizes billing. See
server mounting for the shared handler setup.
Server with optional Link sign-in
The server accepts standard Web Request objects and returns Response
objects asynchronously. It has no Next.js dependency; the host adapts those
objects to its framework. The React browser exports also work independently
of Next.js.
Create one handler with server-only credentials and mount it at
/api/portal/* on the same origin as the React app:
import { createCustomerPortal } from "@stripe/customer-portal/server";
const customerPortal = createCustomerPortal({
stripeSecretKey: process.env.STRIPE_SECRET_KEY!,
authentication: "live",
metronomeApiKey: process.env.METRONOME_API_TOKEN!,
// Credit units and eligible top-ups are discovered automatically.
});
export const GET = customerPortal;
export const POST = customerPortal;
export const PATCH = customerPortal;
export const DELETE = customerPortal;The same customerPortal value checks its HttpOnly session cookie on a host server
route:
const auth = await customerPortal.getAuth(request);
if (!auth.isAuthenticated)
return Response.json({ error: "Sign in required" }, { status: 401 });
// auth.userId is the Stripe cus_… ID.getAuth verifies the JWT signature and expiry with stripeSecretKey. The JWT
contains the Stripe customer ID, Link account ID, email, and display name; a
missing or invalid cookie returns a signed-out result. Routine auth checks do
not call Stripe.
Run customerPortal.validateConfiguration() in a server-only build or CI script
using the same options as the runtime handler. For Stripe-key Metronome access,
pass the Stripe secret key as both stripeSecretKey and metronomeApiKey.
The check reads Stripe and Metronome, rejects incompatible offered packages and
invalid catalog options, and requires exactly one matching direct Stripe
connection for paid plans. It returns { stripeAccountId, currency, packageIds,
topUpsEnabled } without creating customers, contracts, or payments. Any rejected
check should fail the build. Existing customer contracts, webhooks, usage delivery,
and payment success require separate sandbox verification.
After Link verifies an email, sign-in reuses exactly one Stripe Customer with that normalized email, creates one when none exists, and rejects duplicate matches. Existing name, phone, email spelling, and metadata are preserved. The Link account ID remains verification context in the signed session claims. Test authentication uses the same email-based resolution without proving email ownership, so it requires a trusted preview boundary.
For a host usage route, customerPortal.getCustomer(request) verifies that session and
ensures a Metronome customer has the Stripe ID as its ingest alias. It returns
null when signed out, or { id, metronomeCustomerId }. Send id as the
usage event's customer_id; use metronomeCustomerId for Metronome management
API calls. Provider errors reject the call.
For a host action, customerPortal.getUsageAccess(request) checks the current contract
and returns { allowed, mode, metered, reason? }, or null when signed out.
Prepaid usage requires positive credit; postpaid usage does not. Subscription-only
access requires an active subscription term with positive quantity and returns
metered: false. Ingest a usage event only when metered is true. No active
contract denies access. Provider and unsupported-configuration errors reject.
For a prepaid usage gate, customerPortal.getUsageBalance(request) verifies the same
session, ensures provisioning, and returns the fresh net balance and usage
policy. It omits balance entries and product labels. A signed-out request
returns null; provider errors reject. Check the balance before generating
chargeable usage.
Sign-in awaits Metronome provisioning by default. If provisioning fails, the
handler returns an error without issuing a session cookie. To opt into
post-response provisioning, supply backgroundTask. Next.js hosts pass after
from next/server; other hosts supply their own lifecycle callback. The
package does not import Next.js. If registering background work throws, the
handler falls back to awaiting provisioning.
With a scheduler, background failures are logged after sign-in responds; webhooks and billing requests retry missing provisioning. The callback is not a durable queue. Choose background mode only when the host keeps registered work alive after the response.
Stripe-only payment methods, profile, payments, and invoices do not wait for Metronome catalog discovery.
The handler owns the private authentication and billing transport. Configure
webhook delivery through the server SDK options.
It uses stripeSecretKey directly to sign its one-hour session cookies, so
rotating that key invalidates existing sessions. In live mode the package
obtains Link App's publishable key from https://app.link.com/api/app_config,
then sends and verifies a real Link code. To opt into the fixed 000000
verifier for a trusted preview, set authentication: "test". To support a
browser toggle in a trusted preview, use authentication: "live" with
allowTestAuthentication: true on the server and pass the selected
authentication="live" or authentication="test" to CustomerPortalProvider.
Both test opt-ins require a Stripe test secret key (sk_test_… or rk_test_…).
The server rejects live or unrecognized keys when either opt-in is enabled.
For live Stripe billing, use authentication: "live" and leave
allowTestAuthentication false or unset.
The example app uses this toggle. Only Link requests carry the selection;
sessions and billing use the same server configuration. Test identities and
challenges live in server memory; customer and billing records still come
from Stripe and Metronome.
For live billing, use a matching live publishable key, the live webhook endpoint
secret for webhook delivery, and a Metronome billing connection to the same
Stripe account.
The webhook secret is optional for sign-in and billing. Accepting Stripe webhook
deliveries requires the stripeWebhookSecret option. The webhook completes successful
top-ups when the browser does not return. Subscribe to customer.created,
customer.deleted, and payment_intent.succeeded: customer creation provisions
only the Stripe cus_… identity and deletion archives its Metronome customer.
Profile updates are ignored. Sign-in and billing requests also provision the
same identity and assign the starting contract when configured.
It discovers active packages, their rate cards, rated usage products, metrics,
and a shared fiat credit type from Metronome. It offers every active package by
default. Use the optional packages selectors to narrow that list by exact ID or
unique exact name. An uncharged startingPackage is optional: a single eligible
package is assigned automatically; with zero or several eligible packages, the
customer chooses one in Packages. Paid packages require a saved payment method
and a matching Metronome-to-Stripe billing connection.
Top-ups are disabled when topUp is omitted. When enabled, the customer portal resolves one active fixed product and at least one offered usage product. Use topUp.product if the fixed product is ambiguous and topUp.applicableProducts to restrict purchased credits. Selection errors fail the catalog request instead of silently removing top-up capability. The host's usage service remains responsible for enforcing a prepaid cutoff.
Browser
Import the CSS once in the host's root layout. The only provider credential exposed to the browser is a Stripe publishable key. Render the provider in a client component:
"use client";
import type { ReactNode } from "react";
import {
CustomerPortalProvider,
SignIn,
SignedIn,
SignedOut,
UserButton,
type PortalSession,
} from "@stripe/customer-portal/auth/react";
export function AppShell({
stripePublishableKey,
initialSession,
children,
}: {
stripePublishableKey: string;
initialSession: PortalSession | null;
children: ReactNode;
}) {
return (
<CustomerPortalProvider
stripePublishableKey={stripePublishableKey}
initialSession={initialSession}
>
<header className="existing-app-header">
{/* Keep the host's existing logo and navigation. */}
<UserButton brandName="Your product" />
</header>
<SignedOut>
<SignIn brandName="Your product" />
</SignedOut>
<SignedIn>{children}</SignedIn>
</CustomerPortalProvider>
);
}Use <Balance variant="minimal" /> to show only the formatted available amount,
without the card, refresh control, or credit breakdown. The default
variant="full" includes the breakdown. Both load the same provider balance.
Compose Packages, Balance, TopUp, Usage, PaymentMethods, BillingHistory, and BillingInformation on your own pages if you prefer. Each accepts an optional className. CustomerPortal also accepts brandName. Top-up amounts and credit restrictions are set on the server, not on components. CustomerPortal provides six destinations: Profile & sign-in, Overview, Plan, Usage & credits, Payment settings, and Billing history. Only the active page is mounted. Plan stays reachable while its catalog loads or fails, and explains an empty catalog. Add credits appears only when top-ups are enabled, with pending operations recovered after reload or provider redirects.
Navigation uses framework-independent hash locations such as
#portal/plan, #portal/usage?action=top-up, and
#portal/history?tab=invoices&invoice=in_…. Browser Back/Forward and reload keep
page and record selection. defaultPage selects the initial page when no hash
route is present. backHref and backLabel connect the customer portal to the host app.
CustomerPortal opens in a centered, dismissible modal by default and takes over
the full screen on mobile. Closing it with the close button, Escape, or the
backdrop returns focus to the opener. Use open and onOpenChange to control
visibility, or conditionally mount it when an account button is clicked.
layout="embedded" uses its host container height; give the container a bounded
height for independent desktop scrolling. layout="standalone" fills the
desktop viewport. Mobile uses a section selector and scrolls inside the modal.
UserButton accepts optional accountHref and billingHref URLs. When supplied,
its avatar menu offers Manage account, Billing, and Sign out. Without those
links it retains the compact sign-out control. Use onManageAccount and
onBilling callbacks to open a controlled CustomerPortal modal in place; these
callbacks take precedence over their corresponding URLs. The customer portal Profile page displays
the Stripe customer ID and supports name edits through its authenticated
private transport managed by the component. Saving updates the Stripe customer and
refreshes signed session claims without extending expiry. Link identity and
Metronome names and aliases remain unchanged. Sign-in email and billing-contact
information are read-only; sign-out clears this browser's customer portal session.
The Plan pricing table marks the current contract and shows actual recurring terms in that column. Selecting or canceling a plan requires confirmation. Payment methods and billing contact details share a page but remain separate Stripe records. Invoice and payment tabs list Stripe records; Metronome draft estimates appear on Overview. Stripe Payment Element remains responsible for payment/setup collection. Provider API annotations are a Storybook design-review feature and are not shipped in customer-facing pages.
Pass initialSession to CustomerPortalProvider from customerPortal.getAuth() in the
host's server render. In a client-only React app, omit initialSession: the
provider restores the session through its private transport using the HttpOnly cookie and sets
isLoaded when the response arrives. This route verifies the JWT locally; it
does not query Stripe or a session database. useUser() returns user,
isLoaded, and isSignedIn.
useAuth() returns isLoaded, isSignedIn, the Stripe userId, and
signOut(). They start from the server-verified claims and update immediately
after code confirmation. The browser cannot read the HttpOnly cookie.
PortalUser.id is the canonical Stripe
customer ID. PortalUser.linkConsumerId is the separate verified Link account
ID, or a test identity ID in test mode.
Browser WebMCP (experimental)
Configure webMCP on CustomerPortalProvider. Omitting it or passing false
disables tools; an options object enables them. The provider lazily loads the
integration and owns one registry for its signed-in session. There is no separate
public React component or /webmcp/react export.
"use client";
import { useState } from "react";
import { CustomerPortalProvider } from "@stripe/customer-portal/auth/react";
import {
CustomerPortal,
type CustomerPortalNavigationRequest,
} from "@stripe/customer-portal/billing/react";
export function AccountExperience({
publishableKey,
}: {
publishableKey: string;
}) {
const [request, setRequest] =
useState<CustomerPortalNavigationRequest | null>(null);
return (
<CustomerPortalProvider
stripePublishableKey={publishableKey}
webMCP={{
tools: [
"get_balance",
"get_usage",
"get_plan",
"open_portal",
"review_plan",
],
onOpenPortal: setRequest,
}}
>
<CustomerPortal
open={request !== null}
navigationRequest={request ?? undefined}
onOpenChange={(open) => {
if (!open) setRequest(null);
}}
/>
</CustomerPortalProvider>
);
}tools defaults to the eight data tools: get_account, get_capabilities,
get_balance, get_usage, get_plan, list_packages, list_invoices, and
get_invoice. An empty list registers nothing. Add open_portal or
review_plan explicitly and provide onOpenPortal to enable navigation.
Unknown/duplicate names or navigation without a handler are configuration errors.
toolPrefix defaults to customer_portal and accepts 1–48 lowercase ASCII
letters, digits, or underscores, starting with a letter. Independent providers
in one document need different prefixes.
onOpenPortal asks the host to show the existing UI. Pass the supplied request
through to CustomerPortal.navigationRequest; hosts do not construct internal
hash routes. Requests contain an id and either { intent: "open", page } or
{ intent: "review_plan", page: "plan", packageId }. A request ID applies once
per portal mount while open. New IDs can repeat a destination; ordinary rerenders
preserve subsequent manual navigation. Requests received while closed apply when
opened. Existing defaultPage behavior remains when no request is supplied.
Optional onStatusChange reports disabled, loading, signed_out,
unsupported, ready, or a sanitized configuration/registration error. ready
means registration succeeded, not that provider connectivity was verified.
Callbacks can change without re-registering tools.
Every call rechecks the session and uses customer-bound same-origin requests.
Tools accept no customer override. Results are JSON strings with
schemaVersion: 1, status, and either data plus retrievedAt or a sanitized
error. Invoice pagination accepts cursor and limit (1–50, default 20).
Usage covers the provider's current billing period; current rates are not
finalized invoice totals. Retrieval time does not prove rating freshness.
Tokens, Link identity, payment client secrets, and invoice hosted/download URLs
are excluded. Balance, usage, and plan reads can provision missing enrollment
through the existing server flow and are conservatively annotated as not
read-only.
review_plan returns requires_user_action after the host accepts a request to
show plan review. It never submits a plan change or payment. Customers confirm
in the existing UI; payment collection stays in Stripe Payment Element.
For a host without React, use the framework-independent entry point:
import { createCustomerPortalWebMCP } from "@stripe/customer-portal/webmcp";
const bridge = createCustomerPortalWebMCP({
basePath: "/example-app",
tools: ["get_balance", "get_usage", "open_portal"],
onOpenPortal: (request) => app.openAccount(request),
});
await bridge.start();
// Recheck after the host's sign-in/sign-out state changes:
await bridge.refreshSession();
// Terminal cleanup when the integration is removed:
bridge.dispose();This API uses the existing same-origin portal session and takes no server keys. The core runtime has no React, Next.js, or provider SDK dependency. Both APIs invalidate old executions on session changes and clean up registrations.
The adapter targets experimental document.modelContext with abort-signal
cleanup. Unsupported browsers retain normal portal UI. The implemented provider
contract was verified with Chrome 156.0.8078.4 in Docker and Codex CLI 0.161.0
through a window-scoped native WebMCP-to-MCP test bridge. See the
browser API reference.
Generic MCP clients need a browser-aware bridge to reach these tools.
Cross-origin iframe integration is not supported.
The fixture-only harness is owned by Storybook and imports its sample data.
Run npm run dev:webmcp and open port 3105 in T3's built-in browser. It labels
registry-double, native, and unsupported modes; only the explicit double simulates
secure-context support. Native mode keeps the browser's actual support checks.
All portal mutations are blocked and billing reads are intercepted.
Run browser tests only inside Docker:
docker compose run --build --rm e2e npm run test:webmcp-ui
docker compose run --build --rm e2e npm run test:example-uiThe existing e2e image's Chromium establishes registry-double integration
coverage. npm run test:webmcp-native tests a separate Docker OpenChrome browser
through its real CDP WebMCP domain; follow the native runbook for setup and Codex
configuration. Do not launch host Playwright or host Chrome as a fallback. See
the browser API reference.
Styling and Storybook
Pass appearance to CustomerPortalProvider to match your host app:
<CustomerPortalProvider
stripePublishableKey={stripePublishableKey}
appearance={{
theme: "night",
variables: {
colorPrimary: "#a5b4fc",
colorBackground: "#182235",
colorText: "#edf1fa",
colorTextSecondary: "#a7b4cc",
colorBorder: "#36445e",
fontFamily: "Arial, Helvetica, sans-serif",
fontSizeBase: "14px",
spacingUnit: "4px",
borderRadius: "12px",
},
}}
>
<SignIn brandName="Your product" />
</CustomerPortalProvider>This follows Connect embedded components' appearance variables
and Elements' theme presets:
stripe (default), night, and flat. Appearance is exported as a type from
the root, auth, and billing entry points. Supported variables are shown above,
plus colorDanger and colorSidebar. The sidebar brand color is independent of
colorPrimary; six-digit hex values get automatic light/dark navigation contrast.
colorSidebar and colorBorder are not forwarded to Stripe Elements. fontSize remains a deprecated alias for fontSizeBase.
The customer portal defaults to a 14px system font, 4px spacing unit, and 10px
corner radius. See the styling reference
for tokens, component patterns, and the Storybook foundations catalog.
Changing the prop updates mounted components without resetting auth or checkout
state. SignIn and all billing components accept an appearance override;
its theme and individual variables merge with the provider configuration.
Colors derive hover, focus, muted surfaces, and status backgrounds. Appearance
is scoped per component, including menus and dialogs rendered through React
portals, so multiple instances can have different themes on the same page.
The same theme and compatible variables are passed to Stripe Payment Element.
colorBorder is a portal variable and is omitted from Elements configuration.
Host fonts apply to the portal; custom fonts inside Stripe's iframe require
Stripe-supported font loading and cannot inherit a host-only font face.
Arbitrary CSS selector rules are not part of this portal API.
The example app's Minimal, Botanical, Editorial, Noir, Electric, and Terminal
controls demonstrate matching
host and portal styles. The selection stays active during client navigation
between chat and billing. The compiled stylesheet uses cp-prefixed classes and
variables and omits Tailwind Preflight. Existing data-cp-theme="dark" on the
document element remains available when no appearance is supplied. The package
includes a self-hosted Inter variable font and its OFL license.
Storybook's Auth and Billing stories use sample data to show UI states without a customer account. Those presentational views are internal to this repository; connected apps import only the public entry points above.
Develop
Read the repository README and AGENTS.md. From the repository root, run npm run check. The component source was adapted from the shadcn/ui new-york-v4 registry (MIT license). Transition utilities use tw-animate-css (MIT license).
Custom credit units
The customer portal infers a custom unit when package grants or usage rates use it.
Pass balanceCreditType: { name: "AI credits" } to createCustomerPortal to
explicitly select a custom Metronome balance and top-up unit. All offered rate cards must
share its conversion into their common fiat currency. Stripe continues to
collect fiat payments; the customer portal quotes and grants the corresponding custom
quantity. Omit this option to infer the denomination from grants and usage rates; use "fiat" to force fiat balances. See the
integration guide for conversion,
rounding, and fulfillment behavior.
Metronome compatibility
The adapter enforces its compatibility limits internally. Read the server configuration
before selecting packages or provisioning contracts. Configuration errors return
409 / UNSUPPORTED; connected sections display an actionable configuration
alert. Provider outages retain their ordinary retry UI. The limits are scoped to
Metronome-dependent operations; Stripe-only sections can load independently.
Automatic billing capabilities
The same minimal server configuration works with the four supplied Terraform
scenarios. Top-ups are discovered when one eligible fixed credit product and
usage products exist in a two-decimal fiat currency. Default payment limits are
500–50,000 minor units, with presets 1,000, 2,500, and 5,000. Set topUp: false
to disable purchases or provide a topUp object to override these limits.
Explicit top-up options still reject missing or ambiguous required products.
The capabilities response includes balances and usage. Connected portal
sections hide wallets and usage where those capabilities are absent.
Subscription-only plans retain Plan, payment settings, and history. Postpaid
usage-only plans have usage reporting without requiring a wallet.
Multiple grant denominations require explicit package or balance-unit selection; invalid custom conversions fail rather than assuming a 1:1 conversion. A shared Metronome account may still need package selectors to identify this app's catalog.
Preserve host branding and open billing in place
Link verifies identity inside the application's experience. Keep the host's logo,
header, fonts, colors, layout, and core controls. Pass its name to SignIn and
use appearance to match its existing tokens. The sign-in form keeps Link
verification attribution separate from the application heading.
<UserButton brandName="Your product" /> is a compact header control with the
current provider-backed balance and account/billing modal actions by default.
Use showBalance={false} to opt out; unsupported subscription-only balances are
hidden. Loading and unavailable data do not appear as zero. Use callbacks for
host-controlled modals; route links are explicit opt-ins. Do not send users to a
separate billing page or replace the app shell by default.
Live and test Link login controls
Trusted local or staff-only previews support both login modes with an explicit
selector and live selected initially. Set CustomerPortalProvider.authentication
to "live" for real Link verification codes or "test" for simulated verification
using 000000. The server must explicitly set allowTestAuthentication: true
before it accepts browser-selected test login. Pass the browser's selector flag
from trusted server configuration; hiding the selector alone does not authorize
or protect test access. See the getting-started guide's app-shell example.
Changing modes clears an unfinished challenge and code entry. Existing sessions remain valid; sign out to test the other mode. Link login mode does not change Stripe payment-key mode, Metronome environment, account branding, or billing records. Fixed-code verification requires Stripe test credentials and must stay behind a trusted access boundary. Configure a dedicated Metronome sandbox; this guard does not verify the Metronome environment.
Debugging and bug reports
The package ships external JavaScript source maps with embedded TypeScript sources. Bundlers can use them to map portal frames back to the original code. For production browser monitoring, configure your host bundler to generate final application maps and upload those maps to your monitoring service; publishing package maps alone does not configure monitoring. Maps increase installation size, and embedded sources are readable by anyone who installs the package. No provider credentials belong in them.
Set onError on createCustomerPortal and CustomerPortalProvider to receive
caught server failures and browser API/transport/payment-form failures, including
ones the UI displays as a recovery message. Server failures log selected diagnostics
to console.error when no callback is provided. Browser reporting is opt-in.
See diagnostics and reporting for the event contract,
privacy limits, source-map setup, and a bug-report template.
Report package bugs to [email protected], using
@stripe/customer-portal and the installed version in the subject.
The package does not email reports or send telemetry automatically.
License
Customer Portal code is licensed under MIT. The included shadcn/ui, tw-animate-css, and Inter notices apply to their respective third-party assets.
