# Puzzle UI - Full documentation
> TypeScript-first React design system and developer ecosystem for UI, themes, hooks, icons, SEO, authentication, storage, fullstack tools, and project scaffolding.
## Official resources
- Website: https://puzzle-ui.com/
- Documentation: https://puzzle-ui.com/docs/getting-started
- Source repository: https://github.com/senorprogramador/puzzle
## API maturity
Button, ButtonGroup and ToggleGroup have Stable APIs. Storage adapters, Auth, Session, Fullstack and SEO surfaces described in the tutorials are Beta; other UI primitives have component-specific labels. Beta status does not guarantee production readiness.
See https://puzzle-ui.com/docs/tutorials#api-maturity.
## Documentation pages
## About Puzzle
Source: https://puzzle-ui.com/docs/about
Learn what Puzzle UI provides, how its packages fit together, and where to start with the documentation.
Puzzle is a TypeScript-first React design system and developer toolkit. The project brings together reusable interface components, theme tokens, composed page sections, and supporting packages for application development.
## What Puzzle includes
* **React interface building blocks:** [UI components](https://puzzle-ui.com/docs/ui), [theme tokens and provider](https://puzzle-ui.com/docs/theme), [hooks](https://puzzle-ui.com/docs/hooks), and [icons](https://puzzle-ui.com/docs/icons).
* **Page sections:** the [Pieces package](https://puzzle-ui.com/docs/pieces) currently documents Hero layouts and presets.
* **Application capabilities:** framework-independent [authentication](https://puzzle-ui.com/docs/auth), [fullstack auth integrations](https://puzzle-ui.com/docs/fullstack), [storage contracts and adapters](https://puzzle-ui.com/docs/storage), and [SEO utilities](https://puzzle-ui.com/docs/seo).
* **Project setup:** the [project generator](https://puzzle-ui.com/docs/create) and [developer guides](https://puzzle-ui.com/docs/developer) help configure and work with Puzzle projects.
Use the [Getting Started guide](https://puzzle-ui.com/docs/getting-started) to install packages and apply the theme provider. The [Architecture overview](https://puzzle-ui.com/docs/architecture) explains how the packages are separated and how they fit together.
## Project and author
Puzzle is developed in the [Puzzle repository](https://github.com/senorprogramador/puzzle). The site identifies [Sjoerd van den Berg](https://senorprogramador.com) as its author and Señor Programador as its publisher.
## API maturity and security boundaries
Package documentation labels APIs as Stable, Beta, or Experimental according to their current validation and compatibility commitments. The component and package APIs covered by the maturity audit are Stable; any other API classification is documented in its package reference. These labels describe API maturity, not production readiness. Check the [API maturity guide](https://puzzle-ui.com/docs/tutorials#api-maturity) and the component or package reference before adopting an API.
Puzzle authentication packages provide libraries and integration code, not a hosted identity service. Applications still need to configure secure HTTP endpoints, cookie and CSRF handling, storage and secrets, and their own authorization rules. Review the [authentication security guide](https://puzzle-ui.com/docs/auth/security) before deployment.
## Puzzle Architecture
Source: https://puzzle-ui.com/docs/architecture
Understand Puzzle's package boundaries, theme and UI relationship, and application integration layers.
Puzzle is developed as a Bun workspace monorepo with packages separated by responsibility. Applications can compose the packages they need; the repository also contains the documentation site and project tooling.
## Package layers
| Layer | Packages | Responsibility |
| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------- |
| UI foundation | `@puzzle-ui/core`, [`@puzzle-ui/hooks`](https://puzzle-ui.com/docs/hooks), [`@puzzle-ui/icons`](https://puzzle-ui.com/docs/icons) | Shared utilities, React interaction hooks, and icon components. |
| Design system | [`@puzzle-ui/theme`](https://puzzle-ui.com/docs/theme), [`@puzzle-ui/ui`](https://puzzle-ui.com/docs/ui), [`@puzzle-ui/pieces`](https://puzzle-ui.com/docs/pieces) | Theme tokens and provider, reusable components that consume the theme CSS properties, and larger composed sections. |
| Application services | [`@puzzle-ui/auth`](https://puzzle-ui.com/docs/auth), `@puzzle-ui/session`, [`@puzzle-ui/storage`](https://puzzle-ui.com/docs/storage) and storage adapters | Authentication and session contracts with pluggable persistence. |
| Framework integration | [`@puzzle-ui/fullstack`](https://puzzle-ui.com/docs/fullstack) | Browser auth client and React UI, server request handlers, and documented Next.js and TanStack Start adapters. |
| Search metadata | [`@puzzle-ui/seo`](https://puzzle-ui.com/docs/seo) | Metadata, structured data, sitemap and robots utilities, plus framework integrations. |
| Project tooling | [`@puzzle-ui/create`](https://puzzle-ui.com/docs/create) | Interactive application scaffolding and optional framework, theme, and authentication setup. |
The [contributor guide](https://puzzle-ui.com/docs/developer/contributing) lists the repository's package and application directories.
## How the design system fits together
The theme package defines tokens and provides them as CSS custom properties. UI components consume those properties instead of defining a separate theme system. A typical application wraps its interface with [`Theme`](https://puzzle-ui.com/docs/theme/theme-provider) and composes exported components from [`@puzzle-ui/ui`](https://puzzle-ui.com/docs/ui). The [Hero sections](https://puzzle-ui.com/docs/pieces/components/hero) in Pieces compose larger page introductions from these UI building blocks.
```tsx
import { Theme } from "@puzzle-ui/theme";
import { Button, Stack, Text } from "@puzzle-ui/ui";
export function App() {
return (
Build an interface with Puzzle.
);
}
```
## Application integration boundaries
Puzzle Auth separates the authentication core from browser and framework integration. The core accepts storage, session, password-hashing, email, rate-limit, secret-protection, and WebAuthn dependencies through interfaces. Fullstack connects the server-side managers to request handlers and browser-facing React APIs; storage adapters implement persistence for supported backends.
Your application remains responsible for wiring endpoints and deployment configuration, handling cookies and CSRF, supplying secrets and infrastructure, and enforcing application-specific authorization. The [Auth security guide](https://puzzle-ui.com/docs/auth/security) describes the operational boundaries.
The SEO package follows a similar separation: framework-independent metadata, graph, sitemap, and robots utilities are available alongside React components and server/framework adapters. See the [SEO overview](https://puzzle-ui.com/docs/seo) and [framework integration guide](https://puzzle-ui.com/docs/seo/frameworks).
## Maturity
API maturity is package- and component-specific. All documented React
component APIs across UI, Pieces, Theme, Icons, Fullstack, and SEO are Stable
with within-major backward-compatibility intent. Auth, Session, Fullstack,
Auth, Session, Fullstack, Storage, and SEO package-level utilities and adapters
are also Stable with within-major backward-compatibility intent. These labels
describe API stability and validation evidence, not production readiness.
Review the relevant package documentation and
[maturity policy](https://puzzle-ui.com/docs/tutorials#api-maturity) before use.
## Authentication
Source: https://puzzle-ui.com/docs/auth
The @puzzle-ui/auth package provides framework-independent account, session, MFA, and authentication lifecycle primitives for Puzzle applications.
`@puzzle-ui/auth` is the server-side authentication core for Puzzle. It provides storage-backed registration and sign-in, account lifecycle workflows, multi-factor authentication, passkeys, recovery codes, and step-up verification without coupling those features to a web framework.
The package accepts storage, session, password-hashing, email, rate-limit, secret-protection, and WebAuthn dependencies through explicit interfaces. Your application remains responsible for creating secure HTTP endpoints, managing cookies and CSRF, and deciding what authenticated users may do.
## Install
For a complete registration-to-dashboard flow, follow the
[Auth tutorial](https://puzzle-ui.com/docs/tutorials/auth). Auth core, Session and the Fullstack
integrations used there have **Stable** APIs, with within-major
backward-compatibility intent. See the
[maturity policy](https://puzzle-ui.com/docs/tutorials#api-maturity).
#### npm
```bash
npm install @puzzle-ui/auth
```
#### bun
```bash
bun add @puzzle-ui/auth
```
#### pnpm
```bash
pnpm add @puzzle-ui/auth
```
#### yarn
```bash
yarn add @puzzle-ui/auth
```
`@puzzle-ui/auth` depends on `@puzzle-ui/storage`, `@puzzle-ui/session`, and `@simplewebauthn/server`. You provide the storage and session implementations, password hasher, and rate-limit provider.
## Quick start
Create a manager with server-side dependencies, initialize it before serving requests, and keep the returned token on the server boundary so it can be set in a secure, HttpOnly cookie.
```ts
import { StorageAuthManager } from "@puzzle-ui/auth";
const auth = new StorageAuthManager(
{ storage, passwordHasher, rateLimitProvider, sessions },
{ rateLimitKeySecret },
);
await auth.initialize();
const result = await auth.register({
email: "person@example.com",
password: "a-long-unique-password",
ipAddress: trustedClientIp,
});
if ("status" in result) {
// MFA is required; complete the enrollment flow on the server.
} else {
// Set result.token in a secure, HttpOnly cookie. Do not return it in JSON.
}
```
The `StorageAuthManager` creates an authenticated session after registration unless policy requires an MFA enrollment first. A password sign-in can return an MFA challenge instead of a session. See [MFA and step-up](https://puzzle-ui.com/docs/auth/mfa) for how to complete these flows.
## What the package provides
| Area | Description | Documentation |
| ---------------------- | ----------------------------------------------------------------------------------------------------- | -------------------------------------------------------------- |
| Authentication manager | Registration, password sign-in, session lookup, auth-state lookup, and sign-out. | [Configuration](https://puzzle-ui.com/docs/auth/configuration) |
| Account lifecycle | Email verification and change, password reset and change, profile update, deactivation, and deletion. | [Account lifecycle](https://puzzle-ui.com/docs/auth/lifecycle) |
| MFA and passkeys | TOTP, WebAuthn passkeys, recovery codes, mandatory enrollment, and session-bound step-up. | [MFA and step-up](https://puzzle-ui.com/docs/auth/mfa) |
| Deployment security | Storage capabilities, token handling, encryption, rate limits, and production guidance. | [Security](https://puzzle-ui.com/docs/auth/security) |
## Authentication states
`getAuthState(token)` reports the server-side state for an authentication or pending challenge token. Treat only `authenticated` as normal application access.
| Status | Meaning |
| ------------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| `unauthenticated` | No valid authenticated session or pending challenge was found. |
| `primary-authenticated` | A staged-auth state represented in the public state type; it is not returned by the core manager. Do not treat it as full access. |
| `mfa-pending` | Password authentication succeeded and an enrolled factor must be verified. |
| `mfa-enrollment-pending` | Policy requires initial enrollment; no normal session is issued yet. |
| `mfa-enrollment-required` | A valid session exists, but policy requires a factor before protected access. |
| `authenticated` | The session is valid and satisfies the configured email-verification and MFA policy. |
Challenge tokens, like session tokens, are credentials. Keep them server-side and transport them only in appropriately scoped secure, HttpOnly cookies.
## Integrating packages
* [`@puzzle-ui/storage`](https://puzzle-ui.com/docs/storage) provides the adapter used to persist users, credentials, audit records, challenges, recovery codes, and rate-limit counters. Authentication requires the storage capabilities described in [Security](https://puzzle-ui.com/docs/auth/security).
* [`@puzzle-ui/fullstack`](https://puzzle-ui.com/docs/fullstack) provides server handlers, browser clients, cookie and CSRF integration, and framework adapters. The [developer authentication guide](https://puzzle-ui.com/docs/developer/authentication) covers generated application setup.
* Auth also stores authentication audit events; keep credentials and secret values out of logs and telemetry.
## Public exports
The package currently has one public entry point, `@puzzle-ui/auth`, and no documented subpath exports.
| Group | Exports |
| ------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Managers | `StorageAuthManager`, `StorageAuthLifecycleManager`, `StorageAuthMfaManager`, `StorageAuthStepUpManager`, `StorageRateLimitProvider` |
| Providers | `WebCryptoAuthSecretProtector`, `SimpleWebAuthnProvider`, `Pbkdf2PasswordHasher`, `PASSWORD_HASH_ALGORITHMS` |
| Storage | `AUTH_USER_COLLECTION`, `AUTH_CREDENTIAL_COLLECTION`, `AUTH_ACTION_TOKEN_COLLECTION`, `AUTH_AUDIT_COLLECTION`, `AUTH_RATE_LIMIT_COLLECTION`, `AUTH_MFA_FACTOR_COLLECTION`, `AUTH_MFA_CHALLENGE_COLLECTION`, `AUTH_RECOVERY_CODE_COLLECTION`, `AUTH_MFA_STEP_UP_COLLECTION`, `initializeAuthStorage` |
| Errors | `AuthError`, `AuthValidationError`, `AuthInvalidCredentialsError`, `AuthEmailVerificationRequiredError`, `AuthAccountConflictError`, `AuthRateLimitError`, `AuthConfigurationError`, `AuthProviderError`, `AuthSessionError`, `AuthTokenError`, `AuthMfaChallengeError`, `AuthMfaFactorError` |
| Email and crypto utilities | `normalizeEmail`, `normalizeDisplayName`, `generateAuthId`, `generateSecureAuthToken`, `hashAuthToken`, `createRateLimitKey`, `encodeBase32`, `decodeBase32`, `generateTotpSecret`, `generateTotpCode`, `verifyTotpCode`, `createTotpUri` |
| Core auth types | `AuthUser`, `AuthState`, `PasswordCredentialStorageRecord`, `AuthManager`, `AuthManagerOptions`, `AuthManagerDependencies`, `StorageAuthManagerDependencies`, `AuthRateLimitRule`, `AuthRateLimitScopePolicy`, `AuthRateLimitPolicies`, `AuthSession`, `AuthResult`, `AuthRegisterResult`, `AuthSignInResult`, `AuthRegisterInput`, `AuthSignInInput`, `AuthMfaPolicy` |
| Lifecycle and rate-limit types | `AuthActionTokenPurpose`, `AuthActionTokenStorageRecord`, `AuthAuditAction`, `AuthAuditEventStorageRecord`, `AuthRateLimitStorageRecord`, `AuthLifecycleRateLimitAction`, `AuthLifecycleRateLimitPolicy`, `AuthLifecycleRateLimitPolicies`, `AuthLifecycleManagerOptions`, `StorageAuthLifecycleManagerDependencies`, `RequestEmailVerificationInput`, `RequestPasswordResetInput`, `ResetPasswordInput`, `ChangePasswordInput`, `UpdateAuthProfileInput`, `RequestEmailChangeInput`, `DeleteAuthAccountInput`, `DeactivateAuthAccountInput`, `StorageRateLimitProviderOptions` |
| Provider types | `PasswordHash`, `PasswordHashAlgorithm`, `PasswordHasher`, `Pbkdf2PasswordHasherOptions`, `EmailMessage`, `EmailProvider`, `RateLimitProvider`, `ProtectedAuthSecret`, `AuthSecretProtector`, `WebAuthnOptionsJSON`, `WebAuthnRegistrationCredential`, `WebAuthnRegistrationVerification`, `WebAuthnAuthenticationVerification`, `WebAuthnProvider`, `WebCryptoAuthSecretProtectorOptions` |
| MFA types | `AuthMfaFactorType`, `AuthMfaFactorStatus`, `AuthMfaAvailableFactor`, `AuthMfaEnrollmentFactor`, `AuthMfaFactor`, `AuthMfaFactorStorageRecord`, `AuthMfaChallengePurpose`, `AuthMfaChallengeStorageRecord`, `AuthRecoveryCodeStorageRecord`, `AuthMfaPendingResult`, `AuthMfaEnrollmentPendingResult`, `AuthMfaEnrollmentCompleted`, `AuthMfaGateway`, `AuthMfaTotpOptions`, `AuthMfaWebAuthnOptions`, `AuthMfaManagerOptions`, `StorageAuthMfaManagerDependencies`, `BeginTotpEnrollmentInput`, `TotpEnrollmentStarted`, `VerifyTotpEnrollmentInput`, `MfaEnrollmentCompleted`, `BeginRequiredMfaEnrollmentInput`, `VerifyRequiredTotpEnrollmentInput`, `FinishRequiredPasskeyEnrollmentInput`, `BeginPasskeyRegistrationInput`, `PasskeyRegistrationStarted`, `FinishPasskeyRegistrationInput`, `BeginPasskeySignInInput`, `PasskeySignInStarted`, `CompleteMfaSignInInput`, `PasskeyMfaStarted`, `PasskeyMfaCompletedInput`, `RemoveMfaFactorInput`, `RegenerateRecoveryCodesInput` |
| Step-up and storage types | `AuthStepUpChallengeStorageRecord`, `AuthStepUpManagerOptions`, `StorageAuthStepUpManagerDependencies`, `BeginStepUpInput`, `CompleteStepUpInput`, `BeginStepUpPasskeyInput`, `FinishStepUpPasskeyInput`, `AuthStepUpPendingState`, `AuthUserStorageRecord`, `InitializeAuthStorageOptions` |
| Error types | `AuthErrorCode` |
See the [configuration](https://puzzle-ui.com/docs/auth/configuration), [lifecycle](https://puzzle-ui.com/docs/auth/lifecycle), and [MFA](https://puzzle-ui.com/docs/auth/mfa) pages for option defaults and method behavior.
## Auth Configuration
Source: https://puzzle-ui.com/docs/auth/configuration
Configure @puzzle-ui/auth managers, storage, password hashing, sessions, and shared rate limiting.
`@puzzle-ui/auth` is assembled from explicit server-side dependencies instead of a framework global. Configure storage, a session manager, password hashing, and rate limiting first; add the lifecycle and MFA managers for those features.
## Core manager
For complete dependency configuration, password hashing, persistence and HTTP
wiring, follow the [Auth tutorial](https://puzzle-ui.com/docs/tutorials/auth#configuration).
`StorageAuthManager` depends on `StorageAdapter`, `SessionManager`, `PasswordHasher`, and `RateLimitProvider`. The optional `mfa` dependency implements `AuthMfaGateway` and is typically `StorageAuthMfaManager`.
```ts
import {
StorageAuthManager,
StorageRateLimitProvider,
} from "@puzzle-ui/auth";
const rateLimitProvider = new StorageRateLimitProvider(storage);
const auth = new StorageAuthManager(
{ storage, passwordHasher, rateLimitProvider, sessions },
{ rateLimitKeySecret },
);
await auth.initialize();
```
Use a production-quality Argon2id implementation for `PasswordHasher` where your runtime supports it, such as `@node-rs/argon2` on Node.js or `Bun.password`. `AuthManager` accepts `argon2id` and `pbkdf2-sha256` hashes. The session manager comes from `@puzzle-ui/session` and must use secure, persistent storage in production.
### PBKDF2 for Cloudflare Workers
Workers cannot run native Argon2, and pure JavaScript Argon2id exceeds the Free plan's CPU limit. `Pbkdf2PasswordHasher` uses the built-in WebCrypto PBKDF2-SHA256 instead. Workers cap PBKDF2 at 100,000 iterations, below the OWASP recommendation of 600,000, so the hasher requires a secret pepper: the password is keyed with HMAC-SHA256 before derivation, which makes hashes from a leaked database useless without the pepper.
```ts
import { Pbkdf2PasswordHasher } from "@puzzle-ui/auth";
const passwordHasher = new Pbkdf2PasswordHasher({
// 32 random bytes from a Worker secret, never from the database.
pepper: hexToBytes(env.AUTH_PASSWORD_PEPPER_HEX),
});
```
| Option | Type | Default | Description |
| ------------ | ------------ | -------- | ---------------------------------------------------------------------------------------------------------------------------- |
| `pepper` | `Uint8Array` | Required | Secret of at least 32 bytes. Changing it makes every stored password stop verifying. |
| `iterations` | `number` | `100000` | PBKDF2 iterations; at least 100,000. Raise it where your runtime allows; `needsRehash` reports hashes with fewer iterations. |
Prefer Argon2id when your runtime supports it.
`initialize()` registers the auth collections and initializes the optional MFA gateway before the manager can be used. Initialize related managers, including the step-up manager, before exposing their endpoints. If a storage-backed rate limiter uses a custom collection name, initialize that provider as well.
## `AuthManagerOptions`
| Option | Type | Default | Description |
| ----------------------- | ------------------------------------- | ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `rateLimitKeySecret` | `string` | Required | Secret used to derive opaque rate-limit keys; must contain at least 32 characters. Keep it private and stable. |
| `usersCollection` | `string` | `auth_users` | User collection name. |
| `credentialsCollection` | `string` | `auth_credentials` | Password credential collection name. |
| `auditCollection` | `string` | `auth_audit_events` | Authentication audit collection name. |
| `minimumPasswordLength` | `number` | `8` | Minimum registration and password-change length, measured in characters. |
| `maximumPasswordLength` | `number` | `1024` | Maximum password length; input is also capped at 4096 UTF-8 bytes. |
| `requireVerifiedEmail` | `boolean` | `false` | Require an email-verified account to sign in or remain authenticated. Keep aligned with lifecycle and MFA manager configuration. |
| `mfaPolicy` | `AuthMfaPolicy` | `{}` | Set `required` or an asynchronous/synchronous `requiredFor(user)` predicate. Existing active factors are challenged at sign-in even if policy is optional. |
| `rateLimits` | Partial registration/sign-in policies | See defaults below | Override email and IP rate limits independently for registration and sign-in. |
| `clock` | `() => Date` | `() => new Date()` | Clock injection for deterministic tests and controlled environments. |
Default rate limits use fixed windows:
| Action | Scope | Limit | Window |
| ------------ | ----- | ----: | -----------: |
| Registration | Email | 5 | 3600 seconds |
| Registration | IP | 10 | 3600 seconds |
| Sign-in | Email | 10 | 900 seconds |
| Sign-in | IP | 30 | 900 seconds |
## Manager methods
| Method | Input | Result | Description |
| --------------------------- | ------------------------ | ----------------------------- | ---------------------------------------------------------------------------------------------------------- |
| `initialize()` | — | `Promise` | Registers storage and prepares the configured managers. Call before requests. |
| `register(input)` | `AuthRegisterInput` | `Promise` | Creates an account and either an authenticated session or an MFA enrollment challenge. |
| `signIn(input)` | `AuthSignInInput` | `Promise` | Verifies a password and returns an authenticated session, MFA challenge, or required-enrollment challenge. |
| `getCurrentUser(token)` | session token | `Promise` | Returns a user only when the session and current authentication policy are valid. |
| `getAuthState(token)` | session or pending token | `Promise` | Resolves authenticated, unauthenticated, and pending MFA states. |
| `signOut(token)` | session token | `Promise` | Revokes one session. |
| `signOutEverywhere(userId)` | user ID | `Promise` | Revokes all user sessions and pending MFA challenges. |
`AuthRegisterInput` includes `email`, `password`, required `ipAddress`, optional `name`, and optional `sessionMetadata`. `AuthSignInInput` includes `email`, `password`, required `ipAddress`, and optional `sessionMetadata`. Obtain the client IP only through a trusted proxy/application configuration, not an arbitrary client header.
The `AuthResult` token is server-only. Put it in a secure, HttpOnly cookie through your HTTP integration and do not expose it in browser JSON. For framework handlers and cookie/CSRF configuration, see [`@puzzle-ui/fullstack`](https://puzzle-ui.com/docs/fullstack) and the [developer authentication guide](https://puzzle-ui.com/docs/developer/authentication).
## Storage-backed rate limiting
`StorageRateLimitProvider` implements the exported `RateLimitProvider` interface using the auth rate-limit collection and conditional storage updates.
| Option | Type | Default | Description |
| ---------------- | ------------ | ------------------ | ------------------------------------------------------------- |
| `collectionName` | `string` | `auth_rate_limits` | Collection for rate-limit counters. |
| `clock` | `() => Date` | `() => new Date()` | Clock used for window boundaries. |
| `maximumRetries` | `number` | `12` | Maximum storage-conflict retries; must be a positive integer. |
Its constructor requires storage with unique constraints and conditional writes. The `consume({ key, limit, windowSeconds })` method returns `allowed`, `remaining`, and `resetAt`. Use a shared persistent provider across application instances; process-local counters do not coordinate distributed deployments.
## Storage and sessions
`initializeAuthStorage(storage, options?)` registers the default auth collections and optional overrides. Base auth storage requires unique constraints and atomic batches. Lifecycle, MFA, step-up, and the storage-backed rate limiter also require conditional writes where they enforce single-use tokens, atomic transitions, or counters. Confirm the adapter's capabilities in [`@puzzle-ui/storage`](https://puzzle-ui.com/docs/storage) before deploying.
Do not use the auth package's internal collection records as application-level authorization policy. Auth returns the public `AuthUser` shape; application roles, permissions, and resource access checks belong to your application.
## Auth Account Lifecycle
Source: https://puzzle-ui.com/docs/auth/lifecycle
Use @puzzle-ui/auth for email verification, password reset and change, profile updates, email changes, and account closure.
`StorageAuthLifecycleManager` adds account-maintenance workflows to `@puzzle-ui/auth`. It uses the same storage, session manager, password hasher, and shared rate-limit provider as the core manager, plus an `EmailProvider` for verification and reset messages.
## Configure and initialize
```ts
import { StorageAuthLifecycleManager } from "@puzzle-ui/auth";
const lifecycle = new StorageAuthLifecycleManager(
{ storage, passwordHasher, emailProvider, sessions, rateLimitProvider },
{ rateLimitKeySecret },
);
await lifecycle.initialize();
```
The `rateLimitProvider` dependency is optional; when omitted, the lifecycle manager creates a `StorageRateLimitProvider` using its configured rate-limit collection. The storage adapter must support unique constraints, conditional writes, and atomic batches.
## Workflows
| Method | Input | Result | Behavior |
| ------------------------------ | ------------------------------- | ------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| `sendEmailVerification(input)` | `RequestEmailVerificationInput` | `Promise` | Sends a verification message for the specified `userId`; input includes `verificationUrl` and `ipAddress`. |
| `verifyEmail(token)` | token string | `Promise` | Consumes a valid email-verification token and marks the account verified. |
| `requestPasswordReset(input)` | `RequestPasswordResetInput` | `Promise` | Requests a reset using `email`, `resetUrl`, and `ipAddress`. Use a non-enumerating public response. |
| `resetPassword(input)` | `ResetPasswordInput` | `Promise` | Consumes the supplied reset token and sets `newPassword`. |
| `changePassword(input)` | `ChangePasswordInput` | `Promise` | Requires `sessionToken`, `currentPassword`, and `newPassword`. |
| `updateProfile(input)` | `UpdateAuthProfileInput` | `Promise` | Updates the signed-in user's optional `name` and/or `image`. |
| `requestEmailChange(input)` | `RequestEmailChangeInput` | `Promise` | Requires the session and current password; sends confirmation for the requested `email` using `verificationUrl` and `ipAddress`. |
| `verifyEmailChange(token)` | token string | `Promise` | Consumes the confirmation token and applies the new email. |
| `deactivateAccount(input)` | `DeactivateAuthAccountInput` | `Promise` | Deactivates the signed-in account after password confirmation. |
| `deleteAccount(input)` | `DeleteAuthAccountInput` | `Promise` | Deletes the signed-in account after password confirmation. |
Lifecycle methods use the authenticated session for profile, password, email-change, deactivation, and deletion operations. Email verification and password reset use single-use action tokens. Never log the full token or include it in analytics.
## `AuthLifecycleManagerOptions`
| Option | Type | Default | Description |
| --------------------------------------- | -------------------------------- | -------------------- | --------------------------------------------------------------------------------------- |
| `rateLimitKeySecret` | `string` | Required | At least 32 characters; used for opaque rate-limit identifiers. |
| `usersCollection` | `string` | `auth_users` | User records collection. |
| `credentialsCollection` | `string` | `auth_credentials` | Password credential collection. |
| `actionTokensCollection` | `string` | `auth_action_tokens` | Single-use email and password action tokens. |
| `auditCollection` | `string` | `auth_audit_events` | Lifecycle audit events. |
| `rateLimitsCollection` | `string` | `auth_rate_limits` | Storage-backed rate-limit counters when using the default provider. |
| `minimumPasswordLength` | `number` | `8` | Minimum new-password length. |
| `maximumPasswordLength` | `number` | `1024` | Maximum password length, also subject to a 4096 UTF-8 byte limit. |
| `emailVerificationTokenLifetimeSeconds` | `number` | `3600` | Email-verification token lifetime. |
| `passwordResetTokenLifetimeSeconds` | `number` | `3600` | Password-reset token lifetime. |
| `emailChangeTokenLifetimeSeconds` | `number` | `3600` | Email-change token lifetime. |
| `emailTemplates` | Partial template map | See defaults below | Template identifiers passed to the email provider. |
| `emailSubjects` | Partial subject map | See defaults below | Message subjects passed to the email provider. |
| `rateLimits` | `AuthLifecycleRateLimitPolicies` | See defaults below | Override email and IP rules for verification, reset, and email change. |
| `clock` | `() => Date` | `() => new Date()` | Clock injection for tests. |
| `requireVerifiedEmail` | `boolean` | `false` | Align with the core manager's email-verification policy. |
| `onEmailDeliveryError` | `(error: unknown) => void` | Unset | Optional callback for email delivery failures. Do not log secrets from provider errors. |
| `onSessionRevocationError` | `(error: unknown) => void` | Unset | Optional callback for session-revocation failures during lifecycle operations. |
Default template identifiers are `auth/email-verification`, `auth/password-reset`, and `auth/email-change-verification`. Default subjects are “Verify your email address”, “Reset your password”, and “Confirm your new email address”.
The default rate limits for each of email verification, password reset, and email change are 3 requests per email per hour and 10 requests per IP per hour. Public reset endpoints should return the same response whether or not an account exists.
## Email provider contract
Implement the exported `EmailProvider.send(message)` contract. Each message contains `to`, `subject`, `template`, and a string-valued `variables` map. Provide your own delivery, templates, retries, and URL generation. Links must use an application-controlled trusted origin; do not build security-sensitive links from an untrusted `Host` header.
See [`@puzzle-ui/fullstack`](https://puzzle-ui.com/docs/fullstack) for HTTP integration. Pair this page with the [storage guide](https://puzzle-ui.com/docs/storage) for the persistence guarantees required by single-use account action tokens.
## Auth MFA and Step-Up
Source: https://puzzle-ui.com/docs/auth/mfa
Configure TOTP, WebAuthn passkeys, recovery codes, mandatory MFA enrollment, and session-bound step-up authentication with @puzzle-ui/auth.
`StorageAuthMfaManager` implements optional or required multi-factor authentication for `@puzzle-ui/auth`. It supports TOTP authenticator apps, WebAuthn passkeys, and single-use recovery codes. `StorageAuthStepUpManager` uses an additional verified factor to rotate an existing authenticated session after a sensitive action requires recent MFA.
## Configure MFA
For a complete required-enrollment flow that keeps provisioning secrets out of
JSON and React state, follow the [Auth tutorial](https://puzzle-ui.com/docs/tutorials/auth).
Its non-hydrated server HTML flow is intentionally different from the bundled
client enrollment/settings UI.
```ts
import {
SimpleWebAuthnProvider,
StorageAuthManager,
StorageAuthMfaManager,
WebCryptoAuthSecretProtector,
} from "@puzzle-ui/auth";
const secretProtector = new WebCryptoAuthSecretProtector({
currentKeyId: "totp-key-2026",
keys: { "totp-key-2026": encryptionKeyBytes },
});
const mfa = new StorageAuthMfaManager(
{
storage,
sessions,
passwordHasher,
rateLimitProvider,
secretProtector,
webAuthnProvider: new SimpleWebAuthnProvider(),
},
{
rateLimitKeySecret,
webAuthn: {
rpId: "example.com",
rpName: "Example",
origin: "https://example.com",
},
},
);
const auth = new StorageAuthManager(
{ storage, passwordHasher, rateLimitProvider, sessions, mfa },
{ rateLimitKeySecret, mfaPolicy: { required: true } },
);
await auth.initialize();
```
Use a 32-byte `Uint8Array` encryption key sourced from a secret manager, not a literal in application code. If passkeys are disabled, omit both the `webAuthn` option and `webAuthnProvider`. If enabled, configure both together and use the exact production origin and RP ID.
## MFA policy and enrollment
MFA is optional by default. `AuthMfaPolicy.required` requires every user to have and use an active factor; `requiredFor(user)` can require it for selected users. Existing active factors are challenged at sign-in even when MFA policy is optional. A policy that requires MFA without configuring an MFA manager fails closed.
When policy requires a first factor, registration or password sign-in returns `mfa-enrollment-pending` rather than an authenticated session. Complete enrollment through `beginRequiredTotpEnrollment` and `verifyRequiredTotpEnrollment`, or `beginRequiredPasskeyEnrollment` and `finishRequiredPasskeyEnrollment`. Only successful verification completes enrollment and returns an authenticated result plus recovery codes.
For an already authenticated user, factor-management methods require the session token and current password where appropriate. TOTP enrollment is a two-step process:
```ts
const pending = await mfa.beginTotpEnrollment({
sessionToken,
currentPassword,
ipAddress,
label: "Authenticator",
});
// Show pending.otpauthUrl as a QR code or display pending.secret once.
const completed = await mfa.verifyTotpEnrollment({
sessionToken,
factorId: pending.factorId,
code: submittedCode,
ipAddress,
});
// Show completed.recoveryCodes once, then do not persist or log them.
```
The pending TOTP secret is returned so the application can display it during setup; the manager stores its protected representation. Recovery codes are returned only when generated or regenerated. Show them once and ask the user to store them safely.
## MFA methods
| Method | Purpose |
| -------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
| `beginTotpEnrollment` / `verifyTotpEnrollment` | Start and confirm TOTP enrollment for an authenticated session. |
| `beginPasskeyRegistration` / `finishPasskeyRegistration` | Start and verify a passkey registration ceremony. |
| `listFactors(sessionToken)` | List the signed-in user's public factors. |
| `getRecoveryCodeCount(sessionToken)` | Return the remaining unused recovery-code count. |
| `regenerateRecoveryCodes(input)` | Require the current password, invalidate unused prior codes, and return a new set. |
| `removeFactor(input)` | Remove a factor after current-password confirmation. |
| `verifySignInTotp(input)` / `verifySignInRecoveryCode(input)` | Complete a password-backed MFA sign-in challenge. |
| `beginPasskeyMfa(token, ipAddress)` / `finishPasskeyMfa(input)` | Complete password-backed MFA with a passkey. |
| `beginPasskeySignIn(input)` / `finishPasskeySignIn(input)` | Start and complete discoverable passkey sign-in without an email/password step. |
| `beginRequiredTotpEnrollment` / `verifyRequiredTotpEnrollment` | Enroll the first TOTP factor for a required-enrollment challenge. |
| `beginRequiredPasskeyEnrollment` / `finishRequiredPasskeyEnrollment` | Enroll the first passkey for a required-enrollment challenge. |
Passkey methods return WebAuthn options for the browser to use and accept the browser response for server-side verification. Keep challenge tokens in short-lived secure, HttpOnly cookies; do not serialize them into browser JSON or browser storage. The manager validates WebAuthn challenges, origin, RP ID, user verification, and authenticator counters.
TOTP verification prevents reusing an accepted time step. MFA challenges are single-use, expire after the configured lifetime, and are limited to five failed attempts. Recovery codes are single-use and stored as hashes; regeneration invalidates unused prior codes.
## Step-up authentication
Initialize `StorageAuthStepUpManager` with storage, sessions, and the configured MFA manager. `beginStepUp({ sessionToken, ipAddress })` creates a challenge tied to the current session. Complete it using `verifyTotp`, `verifyRecoveryCode`, or `beginPasskey` followed by `finishPasskey`. Completion consumes the challenge, rotates the original session, and returns the replacement session token. Store that token in the same secure cookie boundary as ordinary sessions.
The rotated session metadata includes `authenticationMethod`, `mfaVerifiedAt`, `stepUpVerifiedAt`, and `stepUpOfSessionId`. Your application must enforce its own maximum-age policy by validating the timestamp in trusted server code; the auth package does not authorize business operations automatically. The `AuthStepUpManagerOptions` expose `collectionName` (default `auth_mfa_step_up_challenges`) and an injectable `clock`.
## MFA configuration defaults
| Option | Type | Default | Description |
| -------------------------- | ----------------------------- | --------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| `rateLimitKeySecret` | `string` | Required | At least 32 characters; used to derive rate-limit keys. |
| `usersCollection` | `string` | `auth_users` | User records. |
| `credentialsCollection` | `string` | `auth_credentials` | Password credential records. |
| `auditCollection` | `string` | `auth_audit_events` | Audit events. |
| `factorsCollection` | `string` | `auth_mfa_factors` | TOTP and passkey factor records. |
| `challengesCollection` | `string` | `auth_mfa_challenges` | Hashed, expiring MFA challenges. |
| `recoveryCodesCollection` | `string` | `auth_recovery_codes` | Hashed, single-use recovery codes. |
| `challengeLifetimeSeconds` | `number` | `300` | Challenge lifetime; valid range is 30–600 seconds. |
| `recoveryCodeCount` | `number` | `10` | Codes issued at enrollment or regeneration; valid range is 5–20. |
| `issuer` | `string` | `Puzzle Auth` | TOTP issuer label. |
| `totp` | `Partial` | `{ digits: 6, periodSeconds: 30, window: 1 }` | TOTP digits, period and adjacent time-step window. Allowed ranges: 6–8 digits, 15–120 seconds, and a window from 0–2. |
| `webAuthn` | `AuthMfaWebAuthnOptions` | Unset | Exact `rpId`, `rpName`, and browser `origin`; must be supplied with a WebAuthn provider. |
| `requireVerifiedEmail` | `boolean` | `false` | Require verified email for MFA flows; align with the core and lifecycle managers. |
| `clock` | `() => Date` | `() => new Date()` | Clock injection for tests. |
MFA uses rate limiting as well as short-lived challenges. Verification operations default to 5 attempts per IP and, where known, user in 300 seconds; start operations default to 10 attempts per IP and, where known, user in 900 seconds. Configure a shared rate limiter in production and preserve conditional-write and atomic-batch semantics in the storage adapter.
## Auth Security
Source: https://puzzle-ui.com/docs/auth/security
Review storage, token, password, MFA, WebAuthn, and deployment requirements before exposing @puzzle-ui/auth endpoints.
`@puzzle-ui/auth` provides security-sensitive server-side primitives, not a complete hosted identity service. Your application must configure secure storage and providers, protect session and challenge credentials, and apply authorization checks to each protected operation.
## Production checklist
* Serve authentication endpoints over HTTPS and configure trusted proxy boundaries before resolving client IP addresses.
* Put session and pending-challenge tokens only in secure, HttpOnly cookies with appropriate `SameSite`, path, lifetime, and CSRF controls. Never put tokens in local storage, session storage, logs, analytics, or browser JSON.
* Use a maintained Argon2id password-hashing provider. On runtimes without Argon2id, such as Cloudflare Workers, use `Pbkdf2PasswordHasher` with a secret pepper stored outside the database.
* Use durable shared storage with the required uniqueness, conditional-write, and atomic-batch capabilities. Do not use in-memory storage for production identities, credentials, sessions, factors, tokens, audit events, or rate limits.
* Use a shared persistent rate limiter across server instances. Protect and consistently configure the `rateLimitKeySecret` used to derive opaque counter keys.
* Protect TOTP secrets with `AuthSecretProtector`. `WebCryptoAuthSecretProtector` uses AES-GCM and 32-byte keys; keep keys outside source control, retain old key IDs while records require decryption, and plan key rotation.
* Keep recovery codes hashed at rest, reveal them only at creation/regeneration, and never write them to logs or audit metadata.
* Set exact WebAuthn origins and RP IDs for the deployed site, require HTTPS, and do not trust browser-provided credential metadata without server verification.
* Treat `mfa-enrollment-required`, `mfa-pending`, and `mfa-enrollment-pending` as restricted states. Only `authenticated` represents normal authenticated access.
* Return generic public responses for password-reset requests so callers cannot discover whether an email address has an account.
## Storage guarantees
`initializeAuthStorage` requires unique constraints and atomic batches. The lifecycle and MFA managers additionally require conditional writes and atomic batches to enforce one-time token and challenge consumption; step-up also relies on conditional consumption and atomic session rotation. A storage adapter that advertises a capability must provide its actual concurrency guarantee, not just a best-effort check.
`@puzzle-ui/storage` defines the adapter and capability model. Review the [storage documentation](https://puzzle-ui.com/docs/storage) and verify behavior against your selected database and deployment topology before launch.
## Secrets and token boundaries
Auth action tokens, MFA challenge tokens, recovery codes, and session tokens are bearer credentials. Their hashed or protected persistence representation does not make the cleartext token safe to expose. Return only public user/factor state to browsers, send browser challenge responses to a trusted server endpoint, and keep the cleartext credential inside the cookie/server boundary.
The built-in `WebCryptoAuthSecretProtector` is for TOTP secrets specifically. It uses AES-GCM with authenticated key IDs. Its constructor accepts `{ currentKeyId, keys }`, where each key value must be a 32-byte `Uint8Array`. It does not manage a secret store, rotation schedule, backup, or key-distribution policy for you.
`SimpleWebAuthnProvider` adapts `@simplewebauthn/server` to the exported `WebAuthnProvider` contract. The manager binds challenges and expected origin/RP ID; retain the exact configured origin and RP ID and use the provider's verification results server-side.
## Errors and responses
The package exports `AuthError` and specialized subclasses with stable `code` values, including `INVALID_INPUT`, `INVALID_CREDENTIALS`, `EMAIL_NOT_VERIFIED`, `RATE_LIMITED`, `CONFLICT`, `CONFIGURATION`, `PROVIDER`, `SESSION`, `INVALID_TOKEN`, `MFA_CHALLENGE`, and `MFA_FACTOR`. Do not expose internal provider causes, challenge existence, factor-specific verification failures, or storage details in public responses. Log sanitized operational context only.
## Audit and observability
Core and lifecycle operations write auth audit events to the configured collection. MFA operations also record security-relevant factor and challenge events. Use those records for appropriate audit and incident-response workflows, while applying retention and access control for your environment. Do not treat audit records as application tracing spans or add credential contents to telemetry.
For server handlers, cookie and CSRF integration, and framework adapters, see [`@puzzle-ui/fullstack`](https://puzzle-ui.com/docs/fullstack) and the [developer authentication guide](https://puzzle-ui.com/docs/developer/authentication).
## Scope
`@puzzle-ui/auth` does not provide OAuth or external identity providers, application-specific roles and permissions, authentication pages, or UI components. Compose its managers with your application's authorization policy and use [`@puzzle-ui/fullstack`](https://puzzle-ui.com/docs/fullstack) for HTTP and client integration.
## Create
Source: https://puzzle-ui.com/docs/create
Generate a React application with Puzzle UI, framework-aware theme setup, and optional Tailwind CSS and Puzzle Auth with a working database.
`@puzzle-ui/create` is an interactive command-line generator for new Puzzle applications. It scaffolds a project, configures the Puzzle theme for your framework's router, and can add Tailwind CSS and Puzzle Auth backed by MongoDB or Cloudflare D1. For a guided walkthrough, see [Create a Project](https://puzzle-ui.com/docs/developer/create-project).
## Install
The package is a CLI; run it with your package manager rather than adding it as a project dependency.
#### npm
```bash
npx @puzzle-ui/create
```
#### bun
```bash
bunx @puzzle-ui/create
```
#### pnpm
```bash
pnpm dlx @puzzle-ui/create
```
#### yarn
```bash
yarn dlx @puzzle-ui/create
```
Yarn's `dlx` command requires Yarn 2 or later; with Yarn Classic, use `npx @puzzle-ui/create`. The CLI requires Node.js 20.19 or later, one of npm, Bun, pnpm, or Yarn, and an internet connection to fetch framework templates and dependencies.
## Quick start
Run the generator, answer the prompts, then change into the generated directory and start the dev server. The remaining sections describe the available choices and generated files.
## Interactive setup
The CLI asks the following questions. It has no command-line flags; setup is configured through these prompts.
| Prompt | Type | Default | Description |
| ------------------------------- | --------------- | ------------------------------------ | ------------------------------------------------------------------------------------------ |
| Project name | Text | None (placeholder: `my-awesome-app`) | Required; converted to kebab-case for the directory and package name. |
| Framework | Selection | None | Choose Next.js, TanStack Start, React Router, or Basic React. |
| Install Tailwind CSS? | Confirmation | Yes | Optionally add Tailwind CSS v4 and its framework integration. |
| Add Puzzle Auth? | Confirmation | No | Optionally add the Puzzle Auth client and, for full-stack frameworks, server integration. |
| Database | Selection | MongoDB | Full-stack frameworks with Auth only. Choose MongoDB, Cloudflare D1, or a custom database. |
| First application user email | Text | None | MongoDB and D1 only. Creates the first local application sign-in account. |
| First application user password | Masked password | None | MongoDB and D1 only. Requires 12–1024 characters and at most 4096 UTF-8 bytes. |
| Confirm password | Masked password | None | Must match the supplied password. |
Canceling a prompt cancels project creation. The CLI refuses to create a project if the target directory already exists; it does not overwrite existing files.
## Frameworks and generated structure
Next.js, TanStack Start, and React Router (framework mode) projects are generated with their respective official CLIs. Basic React is generated by Puzzle using React 19, Vite, and TypeScript. The framework generator may supply additional files; the paths below are the Puzzle-specific starter files and configuration.
| Selection | Starter files and configuration |
| ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **Next.js** — Next.js App Router | `src/app/providers.tsx`, `src/app/layout.tsx`, `src/app/page.tsx`, and `next.config.ts`. The providers apply `Theme` with system color mode and map Puzzle `Link` and `Image` to `next/link` and `next/image`. |
| **TanStack Start** — full-stack React | `src/routes/__root.tsx`, `src/routes/index.tsx`, and `vite.config.ts`. The root route applies `Theme` and maps Puzzle `Link` to the TanStack Router `Link`. Unless the project uses D1, the CLI adds [Nitro](https://nitro.build) for a deployable Node.js server, a `start` script, and font cache headers. |
| **React Router** — framework mode | `app/root.tsx`, `app/routes.ts`, `app/routes/home.tsx`, `app/app.css`, and `vite.config.ts`. The root layout applies `Theme` and maps Puzzle `Link` to the React Router `Link`. The template's welcome screen is replaced. |
| **Basic React** — React + Vite + TypeScript | `index.html`, `src/main.tsx`, `src/App.tsx`, `src/index.css`, `vite.config.ts`, and `tsconfig.json` with app and node configs. The entry point applies `Theme`. |
Every starter home page links to the documentation of the Puzzle packages the project uses, so you can jump straight to the relevant guides. Because the framework `Link` is registered through the theme's [component mapping](https://puzzle-ui.com/docs/theme/components), Puzzle `Link` performs client-side navigation for internal routes.
The CLI updates the generated `package.json` name, configures framework package transpilation where needed, and installs `@puzzle-ui/ui` and `@puzzle-ui/theme` using the detected package manager. It detects npm, Bun, pnpm, or Yarn from the package-manager environment; if detection is unavailable, it uses npm.
## Fonts
Every project serves its fonts locally. The CLI writes a default `puzzle-fonts.json` that uses Geist for headings and body text, passes it to `Theme` with `fontSource="local"`, adds a `fonts:download` script, and downloads the Latin and Latin Extended subsets into `public/fonts`.
| Framework | Font configuration |
| ------------------------------------ | ----------------------- |
| Next.js, TanStack Start, Basic React | `src/puzzle-fonts.json` |
| React Router | `app/puzzle-fonts.json` |
Edit the configuration to change fonts, then run `npm run fonts:download` and commit `public/fonts`. See the [Theme CLI](https://puzzle-ui.com/docs/theme/cli) for the configuration format and [Deployment](https://puzzle-ui.com/docs/create/deployment#fonts) for caching.
## Tailwind CSS
Tailwind is enabled by default, but you can opt out. When enabled, the generator installs Tailwind CSS v4 as a development dependency and configures the integration:
| Framework | Configuration |
| -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Next.js | Adds `@import "tailwindcss";` to `src/app/globals.css` and configures `postcss.config.mjs` with `@tailwindcss/postcss`. |
| TanStack Start | Adds the Tailwind import to the stylesheet used by the root route, configures the `@tailwindcss/vite` plugin, and preserves the Puzzle packages in the SSR `noExternal` configuration. |
| React Router | Adds the Tailwind import to `app/app.css` and configures the `@tailwindcss/vite` plugin. |
| Basic React | Adds the Tailwind import to `src/index.css` and configures the `@tailwindcss/vite` plugin. |
The CLI installs `tailwindcss`, `@tailwindcss/postcss`, and `postcss` for Next.js; for the Vite-based frameworks it installs `tailwindcss` and `@tailwindcss/vite`. React Router's template ships with Tailwind, so the CLI removes it when you opt out.
## Puzzle Auth
Puzzle Auth is off by default. When enabled, the CLI installs `@puzzle-ui/auth`, `@puzzle-ui/fullstack`, and `@puzzle-ui/session`, adds an `AuthProvider` with the `/api/auth` base path, and creates sign-in and sign-up views using `AuthExperience`.
### Databases
For Next.js, TanStack Start, and React Router, the CLI asks which database stores users, sessions, and rate-limit counters:
| Database | Generated setup |
| ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **MongoDB** | Installs `@puzzle-ui/storage-mongodb`, the `mongodb` driver, and `@node-rs/argon2`. Adds a `docker-compose.yml` that runs a single-node MongoDB replica set (required for transactions) with access control, a keyfile, and a port bound to `127.0.0.1`. Randomly generated administrator and application passwords are written to `.env`, which `docker compose` reads; the application user can only read and write the project database. Run `npm run db:setup` (or your selected package manager) before `dev` to start the database, initialize missing users, and verify authenticated primary readiness. |
| **Cloudflare D1** | Installs `@puzzle-ui/storage-d1`, hashes passwords with the built-in `Pbkdf2PasswordHasher` and a generated `AUTH_PASSWORD_PEPPER_HEX`, adds `wrangler.jsonc` with a `DB` binding, and wires the Cloudflare runtime: OpenNext for Next.js, and `@cloudflare/vite-plugin` for TanStack Start and React Router. `dev` uses a local D1 database; `preview`, `deploy`, and `cf-typegen` scripts are added. |
| **Custom** | Installs `@puzzle-ui/storage` and leaves a documented placeholder in the database module. Until it returns a storage adapter, the auth API responds with HTTP 503. |
The CLI writes a `.env` file with the database settings, an `APP_ORIGIN` for CSRF checks, and freshly generated `AUTH_ENCRYPTION_KEY_HEX` and `AUTH_RATE_LIMIT_SECRET` secrets (plus `AUTH_PASSWORD_PEPPER_HEX` for D1, and database passwords for MongoDB). `.env` is added to `.gitignore`; never commit it, and set new values in your deployment environment as described in [Deployment](https://puzzle-ui.com/docs/create/deployment).
For MongoDB and D1, the CLI automatically initializes the local database and registers the first application account after installing dependencies. MongoDB requires Docker with Compose to be running. D1 uses the persisted local database used by `dev`, not your remote Cloudflare database. The password is sent through stdin to the generated seed script and stored only as an Auth password hash, never in project files or command-line arguments. Sign in at `/sign-in` when development starts. Puzzle Auth has no built-in administrator roles; this account has normal application permissions. MongoDB administrator credentials remain separate and randomly generated. Repeating bootstrap for an existing email fails rather than resetting its password.
**Deploying to Cloudflare**
Before the first deploy, run `wrangler d1 create ` and
copy the database ID into `wrangler.jsonc`, then store the
secrets with `wrangler secret put`. Keep
`AUTH_PASSWORD_PEPPER_HEX` stable: changing it makes every
existing password stop verifying.
### Routes
Full-stack projects are ready to sign up, sign in, and sign out:
| Route | Purpose |
| ---------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| `/sign-up`, `/sign-in` | `AuthExperience` views that navigate to `/dashboard` after authentication. |
| `/dashboard` | A protected route with MFA settings. It resolves the session on the server and redirects to `/sign-in` when no user is signed in. |
| `/api/auth/*` | The Puzzle Auth API, restricted to the endpoints the generated UI uses. |
| Framework | Auth files |
| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Next.js | `src/app/{sign-in,sign-up,dashboard}/page.tsx`, `src/app/api/auth/[...auth]/route.ts`, `src/components/sign-out-button.tsx`, and server modules under `src/lib/auth/`. |
| TanStack Start | `src/routes/{sign-in,sign-up,dashboard}.tsx`, `src/routes/api/auth/$.ts`, `src/components/sign-out-button.tsx`, and server modules under `src/lib/auth/`. |
| React Router | `app/routes/{sign-in,sign-up,dashboard}.tsx`, `app/routes/api.auth.ts`, `app/components/sign-out-button.tsx`, and `.server.ts` modules under `app/lib/auth/`. |
| Basic React | `src/auth/sign-in.tsx` and `src/auth/sign-up.tsx`. Basic React has no server runtime or API route; host the authentication API separately and configure the client base path for it. |
The server modules read the environment, create the storage adapter and password hasher, and build the `AuthServer` with sessions, rate limiting, MFA, and CSRF protection. Review them against the [Authentication setup guide](https://puzzle-ui.com/docs/developer/authentication) before going to production, in particular the trusted client IP header for your host.
To use a passkey, first sign in with your password and register it in the dashboard's MFA settings. Save the recovery codes shown at enrollment. Passkeys are bound to `APP_ORIGIN` and its hostname, so configure the exact deployed HTTPS origin before registering production passkeys.
## Run your application
After generation and dependency installation complete, run the development script in the new project directory with the selected package manager. For example:
```bash
cd my-awesome-app
npm run dev
```
With Auth and MongoDB, run `npm run db:setup` before `npm run dev`, using your selected package manager. Setup can initialize an older local volume that has no users and create a missing application user when the administrator credentials match. It never resets existing passwords or deletes data. If authentication still fails, restore the original `.env` credentials or update the user password as an administrator; also check exported shell variables, which override Compose's `.env` values. Then open `/dashboard` to try the protected route.
To go to production, follow [Deployment](https://puzzle-ui.com/docs/create/deployment) for your framework and database.
## CLI package details
The package requires Node.js `>=20.19.0` and publishes one executable, `create-puzzle`, at `./dist/index.js`. It does not expose a JavaScript import API or package subpaths. The executable takes no flags; it always starts the interactive setup.
## Deployment
Source: https://puzzle-ui.com/docs/create/deployment
Deploy applications generated by @puzzle-ui/create to production with Next.js, TanStack Start, React Router, or Basic React, using MongoDB, Cloudflare D1, or a custom database.
This guide takes a project generated by [`@puzzle-ui/create`](https://puzzle-ui.com/docs/create) from local development to production. Work through [Before you deploy](https://puzzle-ui.com/docs/create/deployment#before-you-deploy) first, then follow the section for your [database](https://puzzle-ui.com/docs/create/deployment#databases) and [framework](https://puzzle-ui.com/docs/create/deployment#frameworks). Examples use npm; substitute your package manager's `run` command.
## Before you deploy
### Production secrets
The generated `.env` contains secrets for local development. Never commit it and never reuse its values in production. Generate new values for each environment and set them in your host's secret or environment-variable settings:
```bash
# AUTH_ENCRYPTION_KEY_HEX, AUTH_PASSWORD_PEPPER_HEX, and database passwords
openssl rand -hex 32
# AUTH_RATE_LIMIT_SECRET
openssl rand -base64 48
```
| Variable | Production value |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `APP_ORIGIN` | The exact public origin, for example `https://app.example.com`. HTTPS is required outside `localhost`, and there must be no trailing slash. |
| `AUTH_ENCRYPTION_KEY_HEX` | 64 hex characters. Encrypts authenticator (MFA) secrets; existing MFA enrolments stop working if it changes. |
| `AUTH_RATE_LIMIT_SECRET` | At least 32 random characters. |
| `TRUSTED_CLIENT_IP_HEADER` | A client IP header your host or proxy **always overwrites**, such as `cf-connecting-ip` on Cloudflare or `x-real-ip` behind an Nginx proxy you control. Required outside `localhost`. |
| `AUTH_PASSWORD_PEPPER_HEX` | D1 only. 64 hex characters. Keep it stable: changing it makes every existing password stop verifying. |
Next.js, TanStack Start, and React Router read `.env` when it exists, but variables set by your host take precedence. Prefer host-managed variables and do not ship `.env` in images or build artefacts.
### Fonts
Generated projects serve fonts locally. The CLI writes a default `puzzle-fonts.json` and downloads the fonts into `public/fonts` during setup. Commit `public/fonts` so builds do not depend on Google Fonts, and run the download script again whenever you change `puzzle-fonts.json`:
```bash
npm run fonts:download
```
For the best caching, serve versioned `font-.woff2` files with `Cache-Control: public, max-age=31536000, immutable`, and `puzzle-fonts.css` plus the `puzzle-font-.woff2` preload files with a short cache, such as `public, max-age=86400, stale-while-revalidate=604800`. TanStack Start projects apply these headers automatically through [Nitro route rules](https://puzzle-ui.com/docs/theme/cli#cache-headers-with-nitro). On other hosts, configure the same rules in your CDN or web server.
## Databases
The first application account created by the CLI exists only in the local database. It is not automatically provisioned in a separate production database or remote D1. Its password is stored as an Auth password hash, not in generated configuration files. Puzzle Auth has no built-in administrator roles; this account is separate from MongoDB's database administrator.
### MongoDB
Puzzle Auth uses MongoDB transactions, so production MongoDB must be a replica set or sharded cluster.
The generated setup is locked down by default:
* `.env` contains a randomly generated administrator password and a separate application user and password, both 64 hex characters.
* `docker compose` reads the credentials from `.env`; it refuses to start when one is missing.
* Access control is enabled. The replica set authenticates its members with a keyfile generated on first start and stored in the `mongodb-config` volume.
* `docker/mongodb/create-app-user.js` creates the application user on first start with the `readWrite` role on `MONGODB_DATABASE` only. The application never uses the administrator account.
* The `db:setup` package script starts the database and verifies both accounts and replica-set primary readiness. It can initialize the first administrator on an older local volume without users and create a missing application user with matching administrator credentials. Existing passwords and data are never reset.
* The port is published on `127.0.0.1` only, so MongoDB is not reachable from other machines.
#### Managed MongoDB
A managed service such as MongoDB Atlas is the simplest production option. Create a database user with `readWrite` on your application's database only, restrict network access to your application hosts, and set:
```bash
MONGODB_URI="mongodb+srv://:@/?retryWrites=true&w=majority"
MONGODB_DATABASE=""
```
The `MONGODB_ROOT_*` and `MONGODB_APP_*` variables are only used by the generated Docker Compose file and are not needed with a managed service.
#### Self-hosted with Docker Compose
To run the generated `docker-compose.yml` on your server:
1. Copy `docker-compose.yml` and the `docker/mongodb/` directory to the server.
2. Create a `.env` next to them with **new** values for `MONGODB_ROOT_PASSWORD` and `MONGODB_APP_PASSWORD`, and update the password in `MONGODB_URI` to match.
3. Restrict the file: `chmod 600 .env`.
4. Start MongoDB with `docker compose up -d --wait`.
Docker's entrypoint creates users only when the data volume is first initialised. Changing a password in `.env` afterwards does not change it in MongoDB; update it in both places, for example with `db.getSiblingDB("").changeUserPassword("", "")` as the administrator.
For an older local volume without users, run the generated `db:setup` package script from the application directory instead of deleting the volume. If existing users have different credentials, setup refuses to reset them: restore their original `.env` values or update the passwords as an administrator. Exported shell variables override Compose's `.env` values, so check those too.
Run the application on the same server so it can reach `127.0.0.1:27017`. If the application runs as another service in the same Compose project, connect to the `mongodb` service name instead of `localhost`. Never publish port `27017` to the internet. Back up the `mongodb-data` volume, for example with `mongodump`, and keep the `mongodb-config` volume with it.
### Cloudflare D1
D1 projects deploy to Cloudflare Workers. Before the first deploy:
```bash
npx wrangler login
npx wrangler d1 create -db
```
1. Copy the returned `database_id` into `wrangler.jsonc`, replacing the preview ID.
2. Store each secret in the Worker. Do not put secrets in `wrangler.jsonc`:
```bash
npx wrangler secret put AUTH_ENCRYPTION_KEY_HEX
npx wrangler secret put AUTH_RATE_LIMIT_SECRET
npx wrangler secret put AUTH_PASSWORD_PEPPER_HEX
npx wrangler secret put APP_ORIGIN
npx wrangler secret put TRUSTED_CLIENT_IP_HEADER # cf-connecting-ip
```
3. Deploy with `npm run deploy`. This builds the application and runs `wrangler deploy` (or `opennextjs-cloudflare deploy` for Next.js).
D1 access is limited to the `DB` binding of your Worker; there is no database password to manage. Use `npm run preview` to test the Worker build locally before deploying.
### Custom database
Implement the storage adapter in the generated database module. Use a dedicated database user with the minimum privileges Puzzle Auth needs, require TLS for connections that leave the host, keep the database off the public internet, and supply credentials through host-managed environment variables. Until the module returns an adapter, the auth API responds with HTTP 503.
## Frameworks
### Next.js
Build and start the production server on any Node.js host:
```bash
npm run build
npm run start
```
`next start` listens on port 3000; set `PORT` to change it. Run it behind a reverse proxy or load balancer that terminates HTTPS and sets the header named in `TRUSTED_CLIENT_IP_HEADER`.
On a managed platform such as Vercel, add the production variables in the project settings and set `TRUSTED_CLIENT_IP_HEADER` to a header the platform overwrites, such as `x-real-ip` on Vercel.
With D1, the project uses OpenNext for Cloudflare. Follow [Cloudflare D1](https://puzzle-ui.com/docs/create/deployment#cloudflare-d1), then run `npm run deploy`.
### TanStack Start
Node.js projects include [Nitro](https://nitro.build), which builds a standalone server into `.output`:
```bash
npm run build
npm run start
```
`npm run start` runs `node .output/server/index.mjs`. Nitro listens on port 3000 by default; set `PORT` and `HOST` to change it. Copy the whole `.output` directory to deploy; it does not need `node_modules`. Nitro can also build for platforms such as Vercel and Netlify; see its [deployment presets](https://nitro.build/deploy).
The Vite configuration passes `createFontRouteRules()` from `@puzzle-ui/theme/nitro` to Nitro, so local fonts are served with the cache headers described in [Fonts](https://puzzle-ui.com/docs/create/deployment#fonts). The route rules are created from the files in `public/fonts` when the build starts, so download fonts before building.
With D1, the project uses `@cloudflare/vite-plugin` instead of Nitro. Follow [Cloudflare D1](https://puzzle-ui.com/docs/create/deployment#cloudflare-d1), then run `npm run deploy`.
### React Router
Build and start the production server on any Node.js host:
```bash
npm run build
npm run start
```
`npm run start` serves `build/server/index.js` with `react-router-serve`, which listens on port 3000 by default; set `PORT` to change it. Deploy the `build` directory together with `package.json` and production dependencies. The React Router template also includes a `Dockerfile` for container hosts.
With D1, the project runs on Cloudflare Workers and has no `start` script. Follow [Cloudflare D1](https://puzzle-ui.com/docs/create/deployment#cloudflare-d1), then run `npm run deploy`.
### Basic React
Basic React builds a static single-page application:
```bash
npm run build
```
Upload `dist` to any static host or CDN, and rewrite unknown paths to `index.html` if you add client-side routing. Serve `dist/assets/*` with a long immutable cache and fonts as described in [Fonts](https://puzzle-ui.com/docs/create/deployment#fonts).
Basic React has no server runtime. With Auth, host the authentication API separately, ideally on the same site so session cookies stay first-party, and point the `AuthProvider` base path at it.
## Production checklist
* New secrets generated for production and stored in the host, not in `.env` or source control.
* `APP_ORIGIN` set to the exact HTTPS origin.
* `TRUSTED_CLIENT_IP_HEADER` set to a header your host overwrites.
* Database reachable only from the application, with a least-privileged user.
* `public/fonts` committed and up to date with `puzzle-fonts.json`.
* Backups configured for self-hosted databases.
See [Production readiness](https://puzzle-ui.com/docs/auth/security) and the [Authentication setup guide](https://puzzle-ui.com/docs/developer/authentication) for a complete Auth review.
## Developer Tools
Source: https://puzzle-ui.com/docs/developer
Set up Puzzle applications with the project generator, theme CLI, and practical development guides.
Puzzle's developer tools cover application scaffolding and project workflows. They help you get started with the packages; they do not replace framework, deployment, or security configuration.
## Create a project
The interactive [`@puzzle-ui/create` CLI](https://puzzle-ui.com/docs/create) scaffolds a React application with Puzzle UI and Theme. Its prompts support Next.js, TanStack Start, React Router, or Basic React, with optional Tailwind CSS and Puzzle Auth setup.
```bash
bunx @puzzle-ui/create
```
See [Create a Project](https://puzzle-ui.com/docs/developer/create-project) for the setup walkthrough and generated structure. The CLI requires Node.js 20.19 or later and an internet connection to fetch framework templates and dependencies.
## Configure fonts
The [Theme CLI](https://puzzle-ui.com/docs/theme/cli) downloads configured font files for local serving. The project generator creates a font configuration and a download script for generated projects; review the framework-specific setup before adapting it.
## Develop and verify
* [Testing guide](https://puzzle-ui.com/docs/developer/testing): run package checks and understand the repository's validation workflows.
* [Contributing guide](https://puzzle-ui.com/docs/developer/contributing): find package boundaries, repository prerequisites, and project conventions.
* [Authentication setup guide](https://puzzle-ui.com/docs/developer/authentication): connect auth services, storage, server handlers, and client UI.
For package-level behavior and supported integration details, use the relevant [package references](https://puzzle-ui.com/docs/about#what-puzzle-includes). Generated applications still need deployment-specific configuration; for authentication, follow the [security guidance](https://puzzle-ui.com/docs/auth/security).
## Authentication Setup
Source: https://puzzle-ui.com/docs/developer/authentication
Configure the Puzzle Auth client and server integrations generated by @puzzle-ui/create.
Puzzle Auth consists of two packages with separate responsibilities:
* `@puzzle-ui/auth` contains framework-independent authentication
logic.
* `@puzzle-ui/fullstack` provides the browser client, React
components, HTTP handlers, and framework adapters.
The project generator can scaffold the client integration and framework API route for Next.js and TanStack Start.
**Security configuration is required**
The generated authentication integration is not production-ready by itself.
You must supply secure storage, password hashing, rate limiting, session, MFA,
cookie, CSRF, and trusted client IP configuration before exposing
authentication routes.
## Generate an application
Run the Puzzle project generator:
```bash
npx @puzzle-ui/create
```
Choose Next.js or TanStack Start and enable Puzzle Auth.
The generator installs:
```bash
npm install @puzzle-ui/auth @puzzle-ui/fullstack @puzzle-ui/session
```
## Generated client integration
The generator wraps the application in `AuthProvider`.
```tsx
import { AuthProvider } from "@puzzle-ui/fullstack/auth/client";
export const Providers = ({ children }: { children: React.ReactNode }) => (
{children}
);
```
The provider creates the browser authentication client and retrieves authentication state from the server.
Session credentials are managed by secure server cookies. Do not copy session tokens into local storage or session storage.
## Authentication pages
The generator creates sign-in and sign-up pages using `AuthExperience`.
```tsx
import { AuthExperience } from "@puzzle-ui/fullstack/auth/client";
export const SignInPage = () => ;
```
```tsx
import { AuthExperience } from "@puzzle-ui/fullstack/auth/client";
export const SignUpPage = () => ;
```
The experience supports branding, layout, redirects, custom registration fields, and custom submission handling.
See the `@puzzle-ui/fullstack` package documentation for the complete `AuthExperience` API.
## Framework API routes
### Next.js
The generator creates:
```text
src/app/api/auth/[...auth]/route.ts
```
The route delegates to `createNextAuthHandler`.
```ts
import { createNextAuthHandler } from "@puzzle-ui/fullstack/auth/next";
const handlers = createNextAuthHandler({
auth: authServer,
});
export const GET = handlers.GET;
export const POST = handlers.POST;
```
The generated route also calls the application bootstrap and returns HTTP 503 until an AuthServer has been registered.
### TanStack Start
The generator creates:
```text
src/routes/api/auth/$.ts
```
The route delegates to `createTanStackAuthHandler` through the TanStack server route handlers.
Both adapters delegate authentication policy and security-sensitive behavior to the framework-independent authentication packages.
### Basic React
A Basic React project has no server runtime.
The generator creates the AuthProvider and sign-in/sign-up components, but it does not generate a server API route.
Host the Puzzle Auth API in a separate server application. Configure the client base path to point to that API.
## Configure the server
The generated Next.js and TanStack Start projects include these server-only files:
```text
src/lib/auth/
├── server.ts
├── bootstrap.ts
└── unavailable.ts
```
The `server.ts` module exposes two functions:
* `configureAuthServer(server)` registers the configured server.
* `getAuthServer()` returns the registered server or
`null`.
The bootstrap module provides one initialization point. It is intentionally left for your application to complete.
### Create the AuthServer
The fullstack package expects an `AuthServer` assembled from the authentication managers and session configuration.
```ts
import { createAuthServer } from "@puzzle-ui/fullstack/auth/server";
import { configureAuthServer } from "./server";
import {
auth,
mfa,
stepUp,
sessions,
cookie,
csrf,
resolveClientIp,
} from "./auth-managers";
export const initializePuzzleAuth = () => {
configureAuthServer(
createAuthServer({
auth,
mfa,
stepUp,
sessions,
cookie,
csrf,
resolveClientIp,
}),
);
};
```
This example assumes that `auth-managers` exports already initialized and correctly configured dependencies. It is not a complete provider implementation.
Call your application initialization from the generated bootstrap function. Ensure that initialization is safe to run once per server runtime.
## Required security dependencies
### Storage
The storage adapter must support the capabilities required by the authentication and session managers.
At minimum, verify:
* Unique constraints.
* Conditional writes.
* Atomic batch operations.
Do not use an in-memory adapter for production sessions, tokens, MFA factors, or other security-critical state.
### Password hashing
Supply a secure password hashing implementation through the `PasswordHasher` interface.
Use Argon2id where your runtime supports it. On Cloudflare Workers, use the included `Pbkdf2PasswordHasher` with a secret pepper; see [Auth configuration](https://puzzle-ui.com/docs/auth/configuration#pbkdf2-for-cloudflare-workers).
Do not store plaintext passwords. Do not replace the password hasher with a fast general-purpose hash such as SHA-256.
### Rate limiting
Supply a shared atomic rate limiter. A process-local counter is not sufficient for production deployments with multiple instances.
### Session management
Create a `StorageSessionManager` using the same storage adapter and configure appropriate idle and absolute session lifetimes.
### MFA
The MFA manager requires:
* A password hasher.
* A rate-limit provider.
* An authenticated session manager.
* A secret protector for TOTP secrets.
* A WebAuthn provider when passkeys are enabled.
The WebAuthn relying-party ID, name, and origin must match the actual deployment.
### Cookies and CSRF
Use secure, HttpOnly cookies in production. Configure CSRF protection with the application's trusted origins.
### Client IP resolution
The `resolveClientIp` callback must use the deployment's trusted proxy configuration.
Do not blindly trust arbitrary `X-Forwarded-For` values.
## HTTP 503 before configuration
The generated API route deliberately returns a no-store HTTP 503 response when the application has not registered an AuthServer.
This prevents a generated but unconfigured authentication endpoint from appearing to work.
Do not remove this protection or replace it with fake managers.
## Client and server boundaries
Keep these imports separate:
| Code | Allowed entry point |
| ----------------------------- | ------------------------------------ |
| Browser components and hooks | `@puzzle-ui/fullstack/auth/client` |
| Server handlers | `@puzzle-ui/fullstack/auth/server` |
| Next.js adapter | `@puzzle-ui/fullstack/auth/next` |
| TanStack Start adapter | `@puzzle-ui/fullstack/auth/tanstack` |
| Shared serializable contracts | `@puzzle-ui/fullstack/auth/shared` |
Never import server handlers, storage adapters, password hashing implementations, or secrets into browser-facing modules.
## Basic React with a separate API
For a browser-only React application, point the AuthProvider to the server API:
```tsx
```
The API deployment must configure CORS, trusted origins, cookies, and CSRF protection for the browser application's origin.
## Further reading
* [Create a Project](https://puzzle-ui.com/docs/developer/create-project)
* [Contributing](https://puzzle-ui.com/docs/developer/contributing)
* [Testing](https://puzzle-ui.com/docs/developer/testing)
## Contributing
Source: https://puzzle-ui.com/docs/developer/contributing
Set up the Puzzle repository, understand its structure, and contribute changes consistently.
Puzzle is developed as a Bun workspace monorepo. Contributions should be focused, tested, accessible, and consistent with the existing component and package conventions.
When changing public APIs, consult the package documentation and API stability
audit so maturity indicators and compatibility notes remain accurate.
## Prerequisites
* Git.
* Bun 1.4.4 or a compatible newer version.
* Node.js 20.19 or later for the project generator and related tooling.
* Docker with Compose for MongoDB integration tests.
## Clone the repository
```bash
git clone https://github.com/senorprogramador/puzzle.git
cd puzzle
bun install
```
## Repository structure
| Path | Responsibility |
| ------------------------ | --------------------------------------------------------- |
| apps/site | Documentation website |
| apps/playground | Storybook and component playground |
| packages/core | Framework-independent utilities |
| packages/hooks | Reusable React hooks |
| packages/icons | Icon components and utilities |
| packages/theme | Theme provider and design tokens |
| packages/ui | Reusable UI components |
| packages/pieces | Composed UI sections and larger building blocks |
| packages/create | Interactive project generator |
| packages/auth | Framework-independent authentication core |
| packages/session | Session management |
| packages/storage | Storage contracts |
| packages/storage-d1 | Cloudflare D1 storage adapter |
| packages/storage-mongodb | MongoDB storage adapter |
| packages/fullstack | Authentication client, server, and framework integrations |
## Start developing
Start the documentation site:
```bash
bun run site
```
Start the component playground:
```bash
bun run dev
```
Start Storybook:
```bash
bun run storybook
```
## Project conventions
Before changing a package, inspect its existing implementation and the closest related example. Prefer established patterns over introducing new abstractions.
### Components
* Use functional React components and arrow functions.
* Use named exports.
* Keep components generic and router-independent.
* Prefer semantic HTML and native browser behavior.
* Keep public APIs small and composable.
* Preserve existing behavior unless a breaking change is intentional.
### Styling and themes
* Use existing `--puzzle-*` CSS variables.
* Prefer semantic theme tokens over hardcoded values.
* Keep component styles scoped to the component.
* Respect light and dark themes.
* Respect reduced-motion preferences.
* Avoid adding dependencies for small styling or interaction requirements.
### Accessibility
Interactive components should cover:
* Keyboard navigation.
* Focus management and visible focus.
* Screen-reader support.
* Correct ARIA roles and relationships.
* Touch and pointer interactions.
* High-contrast environments.
* Reduced-motion preferences.
Use native HTML semantics where possible. Do not add ARIA attributes that duplicate native browser behavior.
### Tests
Add tests for meaningful behavior and regressions. Follow the test organization used by the package.
Use unit tests for isolated logic, component tests for rendered behavior, and browser tests for interactions that depend on a real browser.
See [Testing](https://puzzle-ui.com/docs/developer/testing) for the available commands.
## Documentation
The documentation site lives in `apps/site`.
UI component pages are organized by category under:
```text
apps/site/content/docs/ui/
```
Theme documentation lives under:
```text
apps/site/content/docs/theme/
```
Developer guides live under:
```text
apps/site/content/docs/developer/
```
When adding a documentation page:
1. Add the MDX page in the appropriate category.
2. Include a title and description in its frontmatter.
3. Include installation or import instructions where relevant.
4. Document the public API and important behavior.
5. Include practical examples.
6. Explain accessibility behavior where relevant.
7. Add the page to the corresponding sidebar configuration.
8. Verify that all documented imports exist.
Use the existing Fumadocs and Puzzle documentation components. Stateful examples should be reusable components rather than duplicated inline implementations.
## Validate your changes
Run the narrowest relevant checks first.
For a full repository validation:
```bash
bun run typecheck
bun run build
bun run vitest
```
For documentation changes:
```bash
bun run --filter "@puzzle-ui/site" typecheck
bun run --filter "@puzzle-ui/site" build
```
For changes to the project generator or its templates, also run the generated project end-to-end suite:
```bash
bun run test:e2e
```
See [Testing](https://puzzle-ui.com/docs/developer/testing) for package-specific test commands and requirements.
## Pull requests
Keep pull requests focused and explain:
* What changed.
* Why the change is needed.
* Which packages or public APIs are affected.
* Which tests and checks were run.
* Any known limitations or follow-up work.
Include screenshots or short recordings when a visual or interaction change is difficult to understand from code alone.
## Create a Project
Source: https://puzzle-ui.com/docs/developer/create-project
Scaffold a React application with Puzzle UI, Theme, optional Tailwind CSS, and optional Puzzle Auth.
The `@puzzle-ui/create` package creates a new React application with Puzzle UI installed and configured.
It supports Next.js, TanStack Start, React Router, and a basic React + Vite application.
## Requirements
* Node.js 20.19 or later.
* npm, Bun, pnpm, or Yarn.
* An internet connection to download framework templates and dependencies.
## Run the generator
### npm
```bash
npx @puzzle-ui/create
```
### Bun
```bash
bunx @puzzle-ui/create
```
### pnpm
```bash
pnpm dlx @puzzle-ui/create
```
### Yarn
```bash
yarn dlx @puzzle-ui/create
```
Yarn's `dlx` command requires Yarn 2 or later. With Yarn Classic, use the npm command.
## Interactive setup
The generator asks for up to five options.
### Project name
Enter a project name. The generator converts it to kebab-case and uses it for the target directory and package name.
### Framework
| Framework | Generated application |
| -------------- | ---------------------------------- |
| Next.js | Next.js App Router with TypeScript |
| TanStack Start | Full-stack React application |
| React Router | React Router in framework mode |
| Basic React | React, Vite, and TypeScript |
Next.js, TanStack Start, and React Router projects are generated using their official CLI tools. The Basic React template is generated directly by Puzzle.
### Tailwind CSS
You can optionally configure Tailwind CSS v4.
When enabled, the generator configures the appropriate integration for the selected framework and installs the required development dependencies.
### Puzzle Auth
You can optionally add Puzzle authentication.
When enabled, the generator installs:
* `@puzzle-ui/auth`
* `@puzzle-ui/fullstack`
* `@puzzle-ui/session`
For Next.js, TanStack Start, and React Router, it also creates:
* An application-level `AuthProvider`.
* Sign-in and sign-up pages.
* A protected `/dashboard` route that redirects to sign-in without a session.
* A framework-specific authentication API route.
* Server-only modules that create the `AuthServer` and its database adapter.
* A `.env` file with the database settings and generated secrets.
For Basic React, it creates the AuthProvider and sign-in/sign-up components. A Basic React application has no server runtime, so its authentication API must be hosted separately.
### Database
Full-stack projects with Auth ask which database to use:
| Database | Setup |
| ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| MongoDB | Uses `@puzzle-ui/storage-mongodb` and a `docker-compose.yml` replica set with access control. Random passwords are generated into `.env`, which Docker Compose reads. |
| Cloudflare D1 | Uses `@puzzle-ui/storage-d1`, a `wrangler.jsonc` D1 binding, and the Cloudflare runtime for local development and deploys. |
| Custom | Leaves a placeholder storage adapter for you to implement. |
With MongoDB or D1, the CLI asks for the first application user's email and a masked password with confirmation, then automatically creates that account in the local database. MongoDB requires Docker with Compose to be running; D1 uses local persisted storage, not remote Cloudflare D1. The password is hashed using Puzzle Auth and is not saved in project files. Open `/sign-in` after `dev` starts. Puzzle Auth has no administrator roles, so this is a normal application account; MongoDB database administrator credentials remain separate and randomly generated. Custom databases and Basic React do not create an initial account. See [Create](https://puzzle-ui.com/docs/create#puzzle-auth) for the generated files and [Deployment](https://puzzle-ui.com/docs/create/deployment) to go to production.
**Review before production**
The generated `.env` contains local preview values. Set real
secrets, database settings, and `APP_ORIGIN` in your deployment
environment, and configure the trusted client IP header for your host.
See [Authentication Setup](https://puzzle-ui.com/docs/developer/authentication) for the full server configuration.
## What gets configured
After framework generation, the CLI:
1. Configures framework package transpilation.
2. Adds the Puzzle theme provider and maps Puzzle `Link` (and `Image` for Next.js) to the framework's components.
3. Creates a starter page that links to the documentation of the installed Puzzle packages.
4. Sets the generated package name.
5. Optionally creates the Puzzle Auth routes, server modules, database setup, and `.env`.
6. Optionally configures and installs Tailwind CSS.
7. Installs the selected Puzzle and database packages.
The target directory must not already exist. The generator never overwrites an existing project.
## Start developing
Move into the generated directory and run its development server.
```bash
cd my-dashboard
npm run dev
```
Use the package manager selected during setup. For example:
```bash
cd my-dashboard
bun run dev
```
If you chose Auth with MongoDB, run `npm run db:setup` (or your selected package manager) before starting development. This starts the database and verifies both accounts and replica-set primary readiness. It can initialize missing users on an older local volume without deleting data or resetting existing passwords.
## Manual installation
Install the UI and theme packages:
```bash
npm install @puzzle-ui/ui @puzzle-ui/theme
```
Add the theme provider at the root of your application.
```tsx
import { Theme } from "@puzzle-ui/theme";
import { Button } from "@puzzle-ui/ui";
const App = () => (
My application
);
export default App;
```
To add the authentication packages:
```bash
npm install @puzzle-ui/auth @puzzle-ui/fullstack @puzzle-ui/session
```
Follow [Authentication Setup](https://puzzle-ui.com/docs/developer/authentication) before exposing authentication routes.
## Troubleshooting
### The project directory already exists
Choose a different project name or remove the existing directory yourself. The generator deliberately refuses to overwrite existing files.
### Framework generation fails
The generator downloads the framework CLI through your selected package manager. Verify that the package manager is installed and can access the package registry.
### Dependency installation fails
Run the failed installation command manually from the generated project directory. Check the package manager output for registry, network, or version errors.
### Authentication returns HTTP 503
The server could not create the `AuthServer`; the server log shows the cause. Check that the `.env` values are present and that the database is reachable. With MongoDB, run `npm run db:setup` (or your selected package manager). If an existing volume has different credentials, restore its original `.env` or update the user password as an administrator; exported shell variables also override Compose's `.env` values. Do not delete the volume to fix authentication. With a custom database, return your storage adapter from the generated database module.
### Tailwind styles are missing
Check that Tailwind was enabled during setup and that the generated CSS entry point is imported by the application.
## Package details
The generator is published as `@puzzle-ui/create`. Its executable is named `create-puzzle`.
The package requires Node.js 20.19 or later.
## Testing
Source: https://puzzle-ui.com/docs/developer/testing
Run unit, component, browser, integration, and documentation checks in the Puzzle monorepo.
Puzzle uses several test runners depending on the package and the type of behavior being tested.
The repository includes:
* Vitest for unit and component tests.
* Node's test runner for several server-side packages.
* Playwright-backed browser tests through Vitest.
* Docker Compose for MongoDB integration tests.
## Install dependencies
From the repository root:
```bash
bun install
```
## Run the repository test command
The root test script builds the packages first, runs package test scripts, runs the project generator tests, and runs the UI browser tests.
```bash
bun run vitest
```
This is the broadest standard test command in the repository.
## Package-specific tests
### UI components
Run unit and component tests:
```bash
bun run --filter "@puzzle-ui/ui" vitest
```
Run only unit tests:
```bash
bun run --filter "@puzzle-ui/ui" test:unit
```
Run only component tests:
```bash
bun run --filter "@puzzle-ui/ui" test:component
```
Run browser tests:
```bash
bun run --filter "@puzzle-ui/ui" test:browser
```
### Pieces
```bash
bun run --filter "@puzzle-ui/pieces" vitest
bun run --filter "@puzzle-ui/pieces" test:browser
```
### Project generator
```bash
bun run --filter "@puzzle-ui/create" test
```
### Generated project end-to-end tests
The project generator has an end-to-end suite that creates every framework, Tailwind, Auth and database combination in a temporary directory. Each project is installed with Bun using the local `@puzzle-ui/*` packages, then:
* builds and typechecks
* downloads its local fonts
* serves the production build
For MongoDB and D1 projects, the suite also runs the sign-up, sign-out and sign-in flows against the running app.
```bash
bun run test:e2e
```
Docker with Compose and network access are required. The suite builds the workspace first and removes the generated projects, containers and volumes when it finishes. Set `PUZZLE_E2E_FILTER` to run specific projects, for example `PUZZLE_E2E_FILTER=tanstack-auth-d1 bun run test:e2e`. See the [create package README](https://github.com/senorprogramador/puzzle/tree/main/packages/create#end-to-end-tests) for all options.
Run it when changing the generator, its templates, or packages used by generated projects.
### Fullstack authentication
Run server-side and unit tests:
```bash
bun run --filter "@puzzle-ui/fullstack" test
```
Run browser tests:
```bash
bun run --filter "@puzzle-ui/fullstack" test:browser
```
### Authentication and storage
Several backend packages use Node's built-in test runner.
```bash
bun run --filter "@puzzle-ui/auth" test
bun run --filter "@puzzle-ui/session" test
bun run --filter "@puzzle-ui/storage" test
bun run --filter "@puzzle-ui/storage-d1" test
```
## MongoDB integration tests
The MongoDB storage adapter uses a dedicated test runner.
```bash
bun run --filter "@puzzle-ui/storage-mongodb" test
```
Docker with Compose must be available. The test script starts its MongoDB test environment on a free localhost port, so a MongoDB already running on port 27017 does not conflict (set `MONGODB_TEST_PORT` to choose the port), and cleans up the container and volume when it finishes.
## Type checking
Run type checks for all packages and the documentation site:
```bash
bun run typecheck
```
Run the documentation site's type check independently:
```bash
bun run --filter "@puzzle-ui/site" typecheck
```
## Build checks
Build all packages:
```bash
bun run build
```
Build the documentation site:
```bash
bun run --filter "@puzzle-ui/site" build
```
The site build also validates its MDX pages and documentation examples.
## Browser test requirements
Browser tests require the Playwright Chromium browser to be installed.
If a browser test fails before reaching the test assertions, verify the Playwright browser installation and the local browser dependencies first.
## Recommended workflow
For a component change:
1. Run the component's unit tests.
2. Run its component tests.
3. Run its browser tests if keyboard, pointer, focus, or other browser behavior changed.
4. Run the package type check.
5. Build the package.
For a documentation change:
1. Verify all imports and links.
2. Run the site type check.
3. Build the documentation site.
For changes affecting shared packages or public APIs, run the broader repository checks.
## Fullstack
Source: https://puzzle-ui.com/docs/fullstack
Browser clients, React authentication UI, server handlers, and framework adapters for Puzzle Auth.
`@puzzle-ui/fullstack` connects Puzzle authentication services to browser applications and server routes. It provides a browser-safe auth client and React components, server-side `Request`/`Response` handlers, and adapters for Next.js and TanStack Start. It complements the framework-independent `@puzzle-ui/auth` and `@puzzle-ui/session` packages rather than replacing them.
The Fullstack package APIs, including the React auth components on
[Client and React](https://puzzle-ui.com/docs/fullstack/client), are Stable with within-major
backward-compatibility intent. This describes API maturity only; it is not a
production-readiness guarantee.
## Install
Follow the [Auth dashboard tutorial](https://puzzle-ui.com/docs/tutorials/auth) for a complete
server/client setup, required MFA enrollment, protected routes and logout.
#### npm
```bash
npm install @puzzle-ui/fullstack react react-dom
```
#### bun
```bash
bun add @puzzle-ui/fullstack react react-dom
```
#### pnpm
```bash
pnpm add @puzzle-ui/fullstack react react-dom
```
#### yarn
```bash
yarn add @puzzle-ui/fullstack react react-dom
```
React and React DOM 19 are required peer dependencies. The `next` and `@tanstack/react-start` peers are optional; install the framework you use to enable its adapter. For server setup, your app will also use `@puzzle-ui/auth`, `@puzzle-ui/session`, and a configured storage backend. See [Auth](https://puzzle-ui.com/docs/auth), [Storage](https://puzzle-ui.com/docs/storage), and the [authentication implementation guide](https://puzzle-ui.com/docs/developer/authentication) for the service and persistence layers.
## Quick start
Wrap the client application in `AuthProvider`. It creates a client using `/api/auth` by default and loads the authentication snapshot from the server.
```tsx
import { AuthProvider } from "@puzzle-ui/fullstack/auth/client";
export const Providers = ({ children }: { children: React.ReactNode }) => (
{children}
);
```
Create and configure an `AuthServer` from your server-side auth and session managers, then connect it to framework routes. The adapters and exact setup are covered in the pages below.
## What the package provides
| Area | Description | Documentation |
| ---------------------- | -------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- |
| Client and React UI | Browser client, provider and hooks, authentication forms, MFA settings, and configurable sign-in/sign-up experience. | [Client and React](https://puzzle-ui.com/docs/fullstack/client) |
| Server handlers | Authentication, MFA, sessions, lifecycle, route map, readiness checks, and step-up helpers. | [Server handlers](https://puzzle-ui.com/docs/fullstack/server) |
| Next.js adapter | `GET` and `POST` handlers for a Next.js route handler. | [Next.js](https://puzzle-ui.com/docs/fullstack/next) |
| TanStack Start adapter | A Request dispatcher or explicit route map for TanStack Start. | [TanStack Start](https://puzzle-ui.com/docs/fullstack/tanstack) |
| Shared contracts | Serializable client snapshots, inputs, and result types shared across runtimes. | [Shared types](https://puzzle-ui.com/docs/fullstack/shared) |
## Package entry points
| Import | Use |
| ------------------------------------ | ---------------------------------------------------------------------------------------------------------- |
| `@puzzle-ui/fullstack/auth/client` | Browser client, React provider, hooks, UI, localization helpers, and passkey browser helpers. |
| `@puzzle-ui/fullstack/auth/server` | Server construction, route map, request/session helpers, MFA and lifecycle handlers, and readiness checks. |
| `@puzzle-ui/fullstack/auth/shared` | Shared TypeScript data contracts only; no runtime values. |
| `@puzzle-ui/fullstack/auth/next` | Next.js route-handler adapter. |
| `@puzzle-ui/fullstack/auth/tanstack` | TanStack Start request-handler adapter. |
There is no package-root import; use one of the exported subpaths above. Keep auth policy and storage configuration in the appropriate lower-level packages, and use Fullstack to connect them to your app. For the end-to-end app setup, continue with the [developer authentication guide](https://puzzle-ui.com/docs/developer/authentication).
## Client and React
Source: https://puzzle-ui.com/docs/fullstack/client
Use the browser authentication client, React provider and hooks, forms, MFA settings, and configurable auth experience.
The `@puzzle-ui/fullstack/auth/client` entry point is browser-safe. `AuthProvider` shares one client and an authentication snapshot with descendants; session credentials remain managed by the server rather than browser storage.
**API maturity: Stable.** The documented React auth components and Fullstack client APIs are covered by tests and are intended to remain backward-compatible within a major version. This is an API commitment, not a guarantee of production readiness in every application.
## Install
Follow the [Auth tutorial](https://puzzle-ui.com/docs/tutorials/auth) to combine these components
with server enforcement. Its stricter provisioning-secret boundary uses
non-hydrated server HTML instead of the bundled TOTP enrollment/settings UI.
#### npm
```bash
npm install @puzzle-ui/fullstack react react-dom
```
#### bun
```bash
bun add @puzzle-ui/fullstack react react-dom
```
#### pnpm
```bash
pnpm add @puzzle-ui/fullstack react react-dom
```
#### yarn
```bash
yarn add @puzzle-ui/fullstack react react-dom
```
React and React DOM 19 are required peer dependencies. The UI is built with `@puzzle-ui/ui`; that dependency is installed with the package.
## Quick start
```tsx
import { AuthProvider, useAuth, useSession, useUser } from "@puzzle-ui/fullstack/auth/client";
export const Providers = ({ children }: { children: React.ReactNode }) => (
{children}
);
export const Account = () => {
const session = useSession();
const user = useUser();
const { signOut } = useAuth();
if (session.isLoading) return
Loading…
;
if (!user) return
Signed out
;
return ;
};
```
`useAuth` must be called below `AuthProvider`; it exposes the client, snapshot, messages, state flags, refresh, and auth/lifecycle actions. `useSession` returns the status, optional MFA state, and loading/authenticated flags. `useUser` returns the current public user or `null`.
## Client options and provider props
`createAuthClient` accepts `AuthClientOptions`. Its default base path is `/api/auth`, and its default fetch credentials mode is `same-origin`.
| Option | Type | Default | Description |
| ------------- | ---------------------------- | --------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `basePath` | `string` | `"/api/auth"` | Absolute same-origin URL path prefix for the server endpoints. Query strings, fragments, and protocol-relative paths are rejected. |
| `credentials` | `"same-origin" \| "include"` | `"same-origin"` | Fetch credentials mode for auth requests. |
| `fetcher` | `typeof fetch` | `fetch` | Fetch implementation used to call the server. |
`AuthProvider` accepts these props:
| Prop | Type | Default | Description |
| ------------------- | ---------------------------------------- | ---------------------- | ----------------------------------------------------------------------------- |
| `children` | `ReactNode` | — | Descendant UI that can access auth context. |
| `client` | `AuthClient` | Created from `options` | Supply an existing client instead of letting the provider create one. |
| `options` | `AuthClientOptions` | — | Options for the provider-created client. |
| `initialSnapshot` | `AuthClientSnapshot` | — | Initial public snapshot, useful when the server already loaded auth state. |
| `locale` | `string` | `"en"` | Locale identifier used to resolve messages. English is the built-in fallback. |
| `messages` | `AuthMessageOverrides` | — | Partial per-message overrides. |
| `onAuthStateChange` | `(snapshot: AuthClientSnapshot) => void` | — | Called when the provider observes an updated snapshot. |
## React components
All components below are exported from the client entry point and require an `AuthProvider` ancestor.
| Component | Purpose | Notable props |
| ------------------ | ----------------------------------------------------------- | ------------------------------------------------------------------------------------- |
| `SignInForm` | Email/password sign-in form. | `className`, `redirectTo`, `onSuccess`, `onForgotPassword`, `onSignUp` |
| `SignUpForm` | Registration form. | `className`, `redirectTo`, `onSuccess`, `onSignIn` |
| `MfaChallengeForm` | Handles the pending MFA challenge. | `className`, `redirectTo`, `onSuccess` |
| `AuthScreen` | Selects sign-in or sign-up UI and supports custom children. | `mode` (`"sign-in"` or `"sign-up"`), `children`, `className`, callbacks, `redirectTo` |
| `MfaSettings` | Manage the signed-in user's MFA factors and recovery codes. | `className` |
`redirectTo` values are restricted to safe, same-origin paths. If no redirect is supplied, use the callbacks or render your own navigation.
## Configurable auth experience
`AuthExperience` combines branded sign-in/sign-up UI and custom registration fields. It displays the MFA challenge when sign-in requires another factor. Use `onSubmit` when the app must persist additional field values itself; custom fields are not added to the auth user model automatically.
```tsx
import { AuthExperience } from "@puzzle-ui/fullstack/auth/client";
export const Register = () => (
(value ? null : "Enter your company."),
},
],
}}
onSubmit={async ({ registration, fields, signUp }) => {
const snapshot = await signUp(registration);
await saveCompany(registration.email, fields.company);
return snapshot;
}}
/>
);
```
| Configuration | Type | Description |
| ------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `mode` | `"sign-in" \| "sign-up"` | Form mode; defaults to `"sign-in"`. |
| `branding` | `AuthExperienceBranding` | Optional `logo`, `title`, and `description` React nodes. |
| `layout` | `AuthExperienceLayout` | Optional class names, header/footer, width (`"sm"`, `"md"`, `"lg"`, `"full"`), and alignment (`"left"`, `"center"`). |
| `redirects` | `AuthExperienceRedirects` | Optional `afterSignIn` and `afterSignUp` paths. Only safe root-relative paths are followed. |
| `fields` | `readonly AuthCustomField[]` | Additional sign-up fields of type text, email, tel, url, number, checkbox, select, or textarea. |
| `offerPasskeyAfterSignIn` | `boolean` | Defaults to `false`. After successful sign-in, offer passkey enrollment before `onSuccess` and `afterSignIn`. Unsupported browsers and users with an existing passkey continue immediately. |
| `onSubmit` | `(input: AuthExperienceSubmitInput) => Promise` | Custom registration flow; receives standard registration values, custom field values, and the normal `signUp` action. |
| `onSuccess`, `onSignIn`, `onSignUp`, `onForgotPassword` | `() => void` | Optional flow callbacks. |
Custom field names must start with a letter, contain only letters, digits, `_` or `-`, and must not use reserved names (`name`, `email`, `password`, `confirmPassword`). `select` fields use `AuthFieldOption` entries. Validation may be synchronous or asynchronous and should return a message for invalid values.
To offer a passkey after login, set `config={{ offerPasskeyAfterSignIn: true, redirects: { afterSignIn: "/dashboard" } }}`. The user can choose **Skip for now** or confirm their current password and register a browser passkey. Enrollment errors remain visible and do not prevent skipping. After registration, any new recovery codes remain visible until the user chooses **Continue**. The login password is not reused or stored. MFA challenges must complete before this optional step; sign-up is unchanged. The optional messages `passkeyOfferDescription`, `passkeyAdded`, and `skip` can be localized through `AuthProvider.messages`.
## Localization and passkeys
English is built in. `getAuthLocale` selects a configured locale or falls back to English; `resolveAuthMessages` merges English defaults, locale messages, and per-message overrides. `AuthMessages` describes the complete message set and `AuthMessageOverrides` is a partial override. `AuthProvider.messages` supports per-message overrides.
`isPasskeySupported` checks browser credential APIs. `startPasskeyRegistration` and `startPasskeyAuthentication` validate the server-provided WebAuthn challenge and invoke the browser ceremony. `createPasskeyBrowserHelpers` allows injecting a `PasskeyBrowserAdapter` for testing or platform-specific integration. Use these through the client methods where possible; the server must verify every assertion and registration.
## Client API
`AuthClient` provides `register`, `signIn`, `signOut`, and `getSnapshot`; TOTP/recovery-code/passkey challenge verification; required and optional MFA enrollment; factor listing/removal and recovery-code regeneration; step-up verification; and email/password lifecycle methods. MFA and lifecycle actions return the typed snapshots/results in [shared types](https://puzzle-ui.com/docs/fullstack/shared). Errors from failed HTTP responses are represented by `AuthClientError`, which includes `status` and `code`.
## Accessibility and security
The forms use semantic form controls and Puzzle UI field components. Preserve their labels and visible validation feedback when styling them. A browser snapshot is public UI state, not authorization: protect data and actions on the server with `@puzzle-ui/auth` and `@puzzle-ui/session`. Never store session credentials in local storage or trust client-supplied identity data.
## Exports
Runtime exports: `AuthClientError`, `createAuthClient`, `createPasskeyBrowserHelpers`, `isPasskeySupported`, `startPasskeyRegistration`, `startPasskeyAuthentication`, `AuthProvider`, `useAuth`, `useSession`, `useUser`, `SignInForm`, `SignUpForm`, `MfaChallengeForm`, `AuthScreen`, `MfaSettings`, `AuthExperience`, `getAuthLocale`, and `resolveAuthMessages`.
Type exports: `AuthClient`, `AuthClientStatus`, `AuthClientUser`, `AuthClientOptions`, `AuthClientSnapshot`, `AuthClientMfaState`, `AuthClientSignInInput`, `AuthClientRegisterInput`, `AuthClientMfaFactor`, `AuthClientTotpEnrollment`, `AuthClientEnrollmentResult`, `AuthClientRecoveryCodesResult`, `AuthClientFactorList`, `PasskeyBrowserAdapter`, `PasskeyBrowserHelpers`, `AuthProviderProps`, `AuthContextValue`, `AuthFormProps`, `SignInFormProps`, `SignUpFormProps`, `MfaChallengeFormProps`, `AuthScreenProps`, `MfaSettingsProps`, `AuthExperienceProps`, `AuthExperienceConfig`, `AuthExperienceBranding`, `AuthExperienceLayout`, `AuthExperienceRedirects`, `AuthCustomField`, `AuthFieldOption`, `AuthFieldValue`, `AuthFieldValues`, `AuthRegistrationInput`, `AuthExperienceSubmitInput`, `AuthLocale`, `AuthMessages`, and `AuthMessageOverrides`.
For server wiring, continue to [Server handlers](https://puzzle-ui.com/docs/fullstack/server) or use a [framework adapter](https://puzzle-ui.com/docs/fullstack/next).
## Next.js adapter
Source: https://puzzle-ui.com/docs/fullstack/next
Mount Puzzle Fullstack authentication handlers in Next.js App Router route handlers.
The `@puzzle-ui/fullstack/auth/next` entry point dispatches the server route map through Next.js-compatible `GET` and `POST` functions. It uses standard Web `Request` and `Response` objects, so the auth server itself remains framework-independent.
## Install
#### npm
```bash
npm install @puzzle-ui/fullstack react react-dom next
```
#### bun
```bash
bun add @puzzle-ui/fullstack react react-dom next
```
#### pnpm
```bash
pnpm add @puzzle-ui/fullstack react react-dom next
```
#### yarn
```bash
yarn add @puzzle-ui/fullstack react react-dom next
```
The package supports Next.js 15 and 16 as an optional peer. React and React DOM 19 are required peers.
## Quick start
For a complete beginner-friendly walkthrough with MongoDB storage, required MFA and a protected page, follow [Add Puzzle Auth to Next.js](https://puzzle-ui.com/docs/tutorials/auth-nextjs).
Create the route file for the same base path you configure in the client. The default is `/api/auth`.
```ts
// app/api/auth/[...auth]/route.ts
import { createNextAuthHandler } from "@puzzle-ui/fullstack/auth/next";
import { authServer } from "@/server/auth";
const handlers = createNextAuthHandler({ auth: authServer });
export const GET = handlers.GET;
export const POST = handlers.POST;
```
`authServer` is created once from the server-side managers; see [Server handlers](https://puzzle-ui.com/docs/fullstack/server). In the client, point `AuthProvider` or `createAuthClient` at the matching path if you change the default:
```tsx
{children}
```
## Adapter options and behavior
| Option | Type | Default | Description |
| ---------- | ------------ | ------------- | ----------------------------------------------- |
| `auth` | `AuthServer` | — | Server instance returned by `createAuthServer`. |
| `basePath` | `string` | `"/api/auth"` | Prefix used to build the route map. |
`createNextAuthRouteHandlers(options)` returns the route map if you prefer to register individual paths. `createNextAuthHandler(options)` returns `{ GET, POST }`; both methods share a dispatcher. Unmatched paths return `404`, unsupported methods return `405` with an `Allow` header, and responses are not cacheable.
| Export | Description |
| ----------------------------- | ------------------------------------------------------------- |
| `createNextAuthRouteHandlers` | Create the underlying pathname-to-method handler map. |
| `createNextAuthHandler` | Create Next-compatible `GET` and `POST` dispatcher functions. |
| `NextAuthIntegrationOptions` | `{ auth: AuthServer; basePath?: string }`. |
| `NextAuthRouteHandler` | `(request: Request) => Promise`. |
| `NextAuthHandlerSet` | Object with `GET` and `POST` route handlers. |
## Production notes
Keep the server instance and its manager dependencies in a server-only module. Do not import this adapter into client components. Configure cookies, CSRF checks, trusted proxy handling, and auth storage in the server layer; the adapter only routes requests. See [Auth](https://puzzle-ui.com/docs/auth), [Storage](https://puzzle-ui.com/docs/storage), and the [authentication guide](https://puzzle-ui.com/docs/developer/authentication).
## Exports
Runtime exports: `createNextAuthRouteHandlers`, `createNextAuthHandler`.
Type exports: `NextAuthIntegrationOptions`, `NextAuthRouteHandler`, `NextAuthHandlerSet`.
For the framework-independent route map, see [Server handlers](https://puzzle-ui.com/docs/fullstack/server).
## Server handlers
Source: https://puzzle-ui.com/docs/fullstack/server
Configure Puzzle authentication handlers, route maps, session helpers, lifecycle endpoints, readiness checks, and step-up protection.
The `@puzzle-ui/fullstack/auth/server` entry point adapts the managers from `@puzzle-ui/auth` and `@puzzle-ui/session` to Web `Request` and `Response` handlers. It does not create your persistence layer or auth policy; configure those services separately. See [Auth](https://puzzle-ui.com/docs/auth), [Storage](https://puzzle-ui.com/docs/storage), and the [authentication guide](https://puzzle-ui.com/docs/developer/authentication).
## Install
The [Auth tutorial](https://puzzle-ui.com/docs/tutorials/auth) shows complete manager configuration,
policy-aware route protection and a deliberately restricted endpoint map.
#### npm
```bash
npm install @puzzle-ui/fullstack react react-dom
```
#### bun
```bash
bun add @puzzle-ui/fullstack react react-dom
```
#### pnpm
```bash
pnpm add @puzzle-ui/fullstack react react-dom
```
#### yarn
```bash
yarn add @puzzle-ui/fullstack react react-dom
```
React and React DOM 19 are required package peers. Server-side setup also needs initialized Puzzle auth, session, and storage services; install/import the packages that own the managers you configure.
## Create the server
Create manager instances using their package contracts, then pass them to `createAuthServer`. The server initializes the managers once before serving a handler; if initialization fails, the request receives a no-store `503` response and initialization can be retried on a later request.
```ts
import { createAuthServer, createAuthRouteHandlers } from "@puzzle-ui/fullstack/auth/server";
import { auth, mfa, stepUp } from "./auth-managers";
import { sessions, cookie, csrf } from "./session";
export const authServer = createAuthServer({
auth,
mfa,
stepUp,
sessions,
cookie,
csrf,
resolveClientIp,
});
export const authRoutes = createAuthRouteHandlers(authServer);
```
`auth`, `mfa`, `stepUp`, `sessions`, `cookie`, `csrf`, and `resolveClientIp` are required. The supplied managers own their initialization. `resolveClientIp` must use the deployment's trusted proxy configuration; do not blindly trust arbitrary `X-Forwarded-For` values.
| Option | Type | Default | Description |
| ------------------- | ------------------------------ | ------- | ----------------------------------------------------------------------------- |
| `auth` | `AuthManager` | — | Core auth manager. |
| `mfa` | `StorageAuthMfaManager` | — | TOTP, recovery-code, and passkey MFA manager. |
| `stepUp` | `StorageAuthStepUpManager` | — | Recent-authentication/step-up manager. |
| `sessions` | `SessionManager` | — | Session persistence and validation manager. |
| `cookie` | `SessionCookieOptions` | — | Session cookie settings from `@puzzle-ui/session`. |
| `csrf` | `CsrfOptions` | — | CSRF policy from `@puzzle-ui/session`. |
| `resolveClientIp` | `(request: Request) => string` | — | Resolve a client IP using trusted deployment proxy settings. |
| `passwordHasher` | `PasswordHasher` | — | Optional auth password-hashing implementation. |
| `emailProvider` | `EmailProvider` | — | Optional email delivery provider. |
| `rateLimitProvider` | `RateLimitProvider` | — | Optional rate-limit provider. |
| `lifecycle` | `AuthLifecycleHandlersOptions` | — | Optional email verification and password lifecycle services and URL builders. |
## Route map
`createAuthRouteHandlers(server, basePath?)` returns a map from pathname to supported HTTP methods. `basePath` defaults to `/api/auth`; trailing slashes are removed. A framework can register these paths directly or use a package adapter.
| Method | Path | Purpose |
| ------ | ----------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- |
| `POST` | `/register` | Register a user. |
| `POST` | `/sign-in` | Password sign-in. |
| `GET` | `/state` | Read the current public auth snapshot. |
| `POST` | `/sign-out` | End the current session. |
| `POST` | `/mfa/sign-in/totp`, `/mfa/sign-in/recovery-code` | Complete sign-in MFA. |
| `POST` | `/mfa/passkey/sign-in/start`, `/mfa/passkey/sign-in/finish` | Begin or complete passkey sign-in. |
| `POST` | `/mfa/passkey/challenge/start`, `/mfa/passkey/challenge/finish` | Begin or complete passkey MFA. |
| `POST` | `/mfa/totp/enrollment/start`, `/mfa/totp/enrollment/finish` | Enroll a TOTP factor. |
| `POST` | `/mfa/passkey/enrollment/start`, `/mfa/passkey/enrollment/finish` | Enroll a passkey. |
| `POST` | `/mfa/enrollment/required/totp/start`, `/mfa/enrollment/required/totp/finish` | Complete required TOTP enrollment. |
| `POST` | `/mfa/enrollment/required/passkey/start`, `/mfa/enrollment/required/passkey/finish` | Complete required passkey enrollment. |
| `GET` | `/mfa/factors` | List MFA factors. |
| `POST` | `/mfa/factors/remove` | Remove an MFA factor. |
| `POST` | `/mfa/recovery-codes/regenerate` | Regenerate recovery codes. |
| `POST` | `/mfa/step-up/start`, `/mfa/step-up/totp`, `/mfa/step-up/recovery-code` | Start or verify a step-up challenge. |
| `POST` | `/mfa/step-up/passkey/start`, `/mfa/step-up/passkey/finish` | Verify step-up using a passkey. |
| `POST` | `/email/verification/request`, `/email/verification/verify` | Request or complete email verification; only when lifecycle handlers are configured. |
| `POST` | `/password/reset/request`, `/password/reset/finish`, `/password/change` | Request/complete reset or change a password; only when lifecycle handlers are configured. |
The optional `lifecycle` configuration requires a `StorageAuthLifecycleManager`, session and CSRF settings, `resolveClientIp`, and `verificationUrl(request)` / `passwordResetUrl(request)` builders. Reset requests use a generic public response to help prevent account enumeration.
## Session and step-up helpers
| Export | Purpose |
| ------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
| `getRequestSession(request, options)` | Validate the session cookie and return a `SessionRecord` or `null`. |
| `protectAuthenticatedRequest(request, csrf)` | Enforce the configured CSRF policy for a state-changing authenticated request. |
| `createSessionResponse` / `clearSessionResponse` | Build responses that set or clear a session cookie using supplied options. |
| `logoutRequest` / `logoutAllRequest` | End one or all sessions for the authenticated request. |
| `hasRecentStepUp(session, maxAgeSeconds?, now?)` | Check whether a session has recent verified step-up. |
| `requireRecentStepUp(request, options, maxAgeSeconds?)` | Validate a session and require recent MFA; throws `AuthStepUpRequiredError` when insufficient. |
Use `requireRecentStepUp` inside sensitive server actions, after the caller has established the appropriate CSRF and authorization policy.
## Readiness checks
`createAuthReadinessHandler({ checks })` returns a `GET`/`HEAD` handler. Each check has a unique lowercase `name` (up to 64 characters) and a synchronous or asynchronous `check` function; `false` or a thrown error marks it unavailable. The handler returns `200` with `ready` or `503` with `unavailable`, with `Cache-Control: no-store`. Avoid putting secrets or sensitive state in check names or results.
## Security and production notes
Configure session cookies and CSRF protection deliberately through `@puzzle-ui/session`; do not rely on defaults you have not reviewed. Only trust forwarded client-IP headers from known proxies. Keep storage credentials and service managers server-only. Protect server actions independently of client-side auth state, and require recent step-up for sensitive actions. The handlers use no-store responses for auth data and keep MFA challenge tokens in cookies rather than exposing the raw token in JSON.
## Exports
Runtime exports: `createAuthServer`, `createAuthRouteHandlers`, `getRequestSession`, `protectAuthenticatedRequest`, `createSessionResponse`, `clearSessionResponse`, `logoutRequest`, `logoutAllRequest`, `MFA_CHALLENGE_COOKIE_NAME`, `serializeMfaChallengeCookie`, `serializeClearedMfaChallengeCookie`, `readMfaChallengeCookie`, `createMfaPendingResponse`, `createMfaChallengeResponse`, `createAuthMfaHandlers`, `hasRecentStepUp`, `requireRecentStepUp`, `AuthStepUpRequiredError`, `createAuthLifecycleHandlers`, and `createAuthReadinessHandler`.
Types include `AuthServerOptions`, `AuthServerHandlers`, `AuthServer`, `AuthHttpMethod`, `AuthRouteHandlerMap`, `AuthMfaHandlersOptions`, `AuthMfaHandlers`, `AuthMfaPendingResponse`, `AuthClientUserResponse`, `AuthLifecycleHandlersOptions`, `AuthLifecycleHandlers`, `SessionRequestOptions`, `SessionResponseOptions`, `AuthReadinessCheck`, `AuthReadinessOptions`, and `AuthReadinessResult`.
For Next.js, see the [Next.js adapter](https://puzzle-ui.com/docs/fullstack/next); for TanStack Start, see the [TanStack Start adapter](https://puzzle-ui.com/docs/fullstack/tanstack).
## Shared types
Source: https://puzzle-ui.com/docs/fullstack/shared
Serializable authentication snapshots, inputs, user data, and results exposed by the shared entry point.
The `@puzzle-ui/fullstack/auth/shared` subpath contains data-only TypeScript contracts used across browser and server code. It has no runtime exports, so import these types when defining app boundaries or passing auth state between runtimes. The client entry point re-exports most client-facing contracts; `AuthClientLifecycleResult` is available from this shared subpath.
## Install
#### npm
```bash
npm install @puzzle-ui/fullstack react react-dom
```
#### bun
```bash
bun add @puzzle-ui/fullstack react react-dom
```
#### pnpm
```bash
pnpm add @puzzle-ui/fullstack react react-dom
```
#### yarn
```bash
yarn add @puzzle-ui/fullstack react react-dom
```
React and React DOM 19 are required peers by the package, including when you only consume shared types.
## Import types
```ts
import type {
AuthClientSnapshot,
AuthClientStatus,
AuthClientUser,
AuthClientRegisterInput,
AuthClientLifecycleResult,
} from "@puzzle-ui/fullstack/auth/shared";
```
## Contracts
| Type | Description |
| ------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
| `AuthClientStatus` | UI state: `loading`, `unauthenticated`, MFA or enrollment pending states, `step-up-pending`, or `authenticated`. |
| `AuthClientUser` | Public user fields: `id`, `email`, nullable `name` and `image`, and `emailVerified`. |
| `AuthClientMfaState` | Pending MFA purpose, challenge ID, expiry, and optional available factor types. |
| `AuthClientOptions` | Browser client `basePath`, fetch `credentials`, and optional `fetcher`. |
| `AuthClientSnapshot` | `status`, public `user` or `null`, and optional MFA state. |
| `AuthClientSignInInput` | Email and password sign-in fields. |
| `AuthClientRegisterInput` | Email, password, and optional nullable name. |
| `AuthClientMfaFactor` | Factor ID, type, status, label, creation time, and last-use time. |
| `AuthClientTotpEnrollment` | TOTP enrollment status, factor ID, secret, `otpauthUrl`, and expiry. Treat the secret as sensitive. |
| `AuthClientEnrollmentResult` | Added factor and one-time recovery codes. Display and store recovery codes securely. |
| `AuthClientRecoveryCodesResult` | Newly regenerated recovery codes. |
| `AuthClientFactorList` | Active/pending factors and recovery-code count. |
| `AuthClientLifecycleResult` | Status for verification request/completion and password reset/change results. |
These are public response contracts, not proof that a user is authorized for an operation. Enforce access control on the server and avoid exposing enrollment secrets or recovery codes beyond the authenticated flow.
## Exports
Type-only exports: `AuthClientStatus`, `AuthClientUser`, `AuthClientMfaState`, `AuthClientOptions`, `AuthClientSnapshot`, `AuthClientSignInInput`, `AuthClientRegisterInput`, `AuthClientMfaFactor`, `AuthClientTotpEnrollment`, `AuthClientEnrollmentResult`, `AuthClientRecoveryCodesResult`, `AuthClientFactorList`, and `AuthClientLifecycleResult`.
See the [client API](https://puzzle-ui.com/docs/fullstack/client) for provider and browser usage, or the [server handlers](https://puzzle-ui.com/docs/fullstack/server) for server-side contracts.
## TanStack Start adapter
Source: https://puzzle-ui.com/docs/fullstack/tanstack
Connect Puzzle Fullstack auth routes to TanStack Start server handlers using Web Request and Response APIs.
The `@puzzle-ui/fullstack/auth/tanstack` entry point provides either a single request dispatcher or the underlying pathname-to-method route map. It keeps auth logic independent from TanStack Start; your server route passes its incoming Web `Request` to the dispatcher.
## Install
#### npm
```bash
npm install @puzzle-ui/fullstack react react-dom @tanstack/react-start
```
#### bun
```bash
bun add @puzzle-ui/fullstack react react-dom @tanstack/react-start
```
#### pnpm
```bash
pnpm add @puzzle-ui/fullstack react react-dom @tanstack/react-start
```
#### yarn
```bash
yarn add @puzzle-ui/fullstack react react-dom @tanstack/react-start
```
`@tanstack/react-start` is an optional peer. React and React DOM 19 are required peers.
## Quick start
For a complete beginner-friendly walkthrough with MongoDB storage, required MFA and a protected page, follow [Add Puzzle Auth to TanStack Start](https://puzzle-ui.com/docs/tutorials/auth-tanstack-start).
Create the server instance once, then call the handler from the TanStack Start server route that owns the configured base path. The default base path is `/api/auth`.
```ts
import { createTanStackAuthHandler } from "@puzzle-ui/fullstack/auth/tanstack";
import { authServer } from "./auth";
export const handleAuthRequest = createTanStackAuthHandler({
auth: authServer,
});
// In the framework route's GET/POST callback:
export const handleRequest = (request: Request) => handleAuthRequest(request);
```
This generic callback illustrates the adapter boundary: wire `handleAuthRequest` to your TanStack Start server route API and pass its incoming `Request`. The exact route-file declaration depends on your application's TanStack Start setup. Create `authServer` using the [server handler configuration](https://puzzle-ui.com/docs/fullstack/server).
## Options and route map
| Option | Type | Default | Description |
| ---------- | ------------ | ------------- | ----------------------------------------------- |
| `auth` | `AuthServer` | — | Server instance returned by `createAuthServer`. |
| `basePath` | `string` | `"/api/auth"` | Prefix used to build the route map. |
`createTanStackAuthHandler(options)` returns `(request: Request) => Promise`. `createTanStackAuthRouteHandlers(options)` returns the path map when the application needs to register each route explicitly. The dispatcher handles `GET` and `POST`, responds `404` to unknown paths, and responds `405` with an `Allow` header when a route does not support the method.
| Export | Description |
| --------------------------------- | ----------------------------------------------------- |
| `createTanStackAuthRouteHandlers` | Create the underlying pathname-to-method handler map. |
| `createTanStackAuthHandler` | Create a single Request dispatcher. |
| `TanStackAuthIntegrationOptions` | `{ auth: AuthServer; basePath?: string }`. |
## Production notes
Keep the auth server and its manager dependencies in server-only modules. The adapter does not configure storage, session cookies, CSRF protection, or auth policy. See [Auth](https://puzzle-ui.com/docs/auth), [Storage](https://puzzle-ui.com/docs/storage), and the [authentication guide](https://puzzle-ui.com/docs/developer/authentication).
## Exports
Runtime exports: `createTanStackAuthRouteHandlers`, `createTanStackAuthHandler`.
Type exports: `TanStackAuthIntegrationOptions`.
For Next.js, see the [Next.js adapter](https://puzzle-ui.com/docs/fullstack/next); for the shared server route definitions, see [Server handlers](https://puzzle-ui.com/docs/fullstack/server).
## Getting Started
Source: https://puzzle-ui.com/docs/getting-started
Install Puzzle in your React app, build your first interface, and customize the theme.
Puzzle is a TypeScript and React UI component library built around reusable components and shared design tokens. Its components are composable and router-independent, with styling supplied by `@puzzle-ui/theme`.
**API maturity**
UI component API maturity is labeled on each component page. Check package
guides for API maturity, compatibility details, and accessibility notes
relevant to the components and integrations you use.
## Prerequisites
For complete application workflows, explore the [SEO, Auth, and Storage
tutorials](https://puzzle-ui.com/docs/tutorials).
* A package manager: npm, Bun, pnpm, or Yarn.
* An existing React application with a bundler that supports CSS imports, such as Vite.
* React and React DOM 19.
## Install Puzzle
Install the UI and theme packages in your application's directory.
#### npm
```bash
npm install @puzzle-ui/ui @puzzle-ui/theme
```
#### bun
```bash
bun add @puzzle-ui/ui @puzzle-ui/theme
```
#### pnpm
```bash
pnpm add @puzzle-ui/ui @puzzle-ui/theme
```
#### yarn
```bash
yarn add @puzzle-ui/ui @puzzle-ui/theme
```
These commands install published packages. They do not clone the repository or build its workspaces. Puzzle does not require Bun in your application.
## Your first interface
Import components from `@puzzle-ui/ui` and wrap your application in `Theme` from `@puzzle-ui/theme`.
```tsx
import { Theme } from "@puzzle-ui/theme";
import { Button } from "@puzzle-ui/ui";
export const App = () => (
Hello, Puzzle
Build your interface with reusable components and shared tokens.
);
```
`Theme` applies the default tokens and global styles, and follows the
user's system light/dark preference. Use one root theme for your application.
Component styles are imported by the components themselves. Your application bundler must support CSS imports.
See [Button](https://puzzle-ui.com/docs/ui/actions/button) for variants, sizes, and API details.
## Customize your theme
Set the color mode, choose a color palette, load fonts, or override individual tokens.
```tsx
```
Font configuration can load stylesheets from Google Fonts. Omit `fonts` if you do not want external font requests.
In your own CSS, use the same semantic tokens as Puzzle components.
```css
.welcome-panel {
color: var(--puzzle-color-text);
background: var(--puzzle-color-surface);
padding: var(--puzzle-space-4);
border-radius: var(--puzzle-radius-md);
}
```
Read the [Theme overview](https://puzzle-ui.com/docs/theme), [Theme Provider](https://puzzle-ui.com/docs/theme/theme-provider), and [Design Tokens](https://puzzle-ui.com/docs/theme/tokens) guides for configuration details.
## Build your application
Puzzle ships compiled JavaScript and CSS, so you do not need to build the library yourself. Use your application's existing build script.
#### npm
```bash
npm run build
```
#### bun
```bash
bun run build
```
#### pnpm
```bash
pnpm run build
```
#### yarn
```bash
yarn run build
```
Your application must retain CSS imports when bundling Puzzle. No separate Puzzle stylesheet import or Tailwind setup is required.
Framework and server-rendering compatibility is still being evaluated. Test your chosen components in your application's environment.
## Next steps
* Explore [Buttons](https://puzzle-ui.com/docs/ui/actions/button), [Cards](https://puzzle-ui.com/docs/ui/data-display/card), and [Text Inputs](https://puzzle-ui.com/docs/ui/forms/text-input).
* Learn how to configure [colors](https://puzzle-ui.com/docs/theme/colors) and [typography and fonts](https://puzzle-ui.com/docs/theme/typography).
* Try the interactive documentation examples before composing a larger interface.
* Use the [project generator](https://puzzle-ui.com/docs/developer/create-project) to scaffold a new application.
## Hooks
Source: https://puzzle-ui.com/docs/hooks
Reusable React hooks for keyboard shortcuts and accessible roving focus.
`@puzzle-ui/hooks` provides small, composable hooks for keyboard interactions and composite widgets. Its hooks manage browser listeners and focus state while leaving markup and visual styling to your application.
## Install
#### npm
```bash
npm install @puzzle-ui/hooks
```
#### bun
```bash
bun add @puzzle-ui/hooks
```
#### pnpm
```bash
pnpm add @puzzle-ui/hooks
```
#### yarn
```bash
yarn add @puzzle-ui/hooks
```
React `^19.0.0` is a peer dependency and should already be installed in your application.
## Quick start
Import the hooks you need from the package root. `useKeyboardKeys` listens for selected keyboard keys; `useRovingFocus` coordinates arrow-key navigation and tab stops among related elements.
```tsx
import { useKeyboardKeys } from "@puzzle-ui/hooks";
function EscapeShortcut() {
useKeyboardKeys({
keys: ["Escape"],
onKeyDown: () => console.log("Escape pressed"),
});
return null;
}
```
## Hooks
| Hook | Purpose | Reference |
| ----------------- | ----------------------------------------------------------------------------------- | ------------------------------------------------------------------- |
| `useKeyboardKeys` | Subscribe to selected `keydown` and `keyup` events on `window`. | [Keyboard Keys](https://puzzle-ui.com/docs/hooks/use-keyboard-keys) |
| `useRovingFocus` | Implement roving tab stops and arrow-key navigation for a group of focusable items. | [Roving Focus](https://puzzle-ui.com/docs/hooks/use-roving-focus) |
## Exports
The package root, `@puzzle-ui/hooks`, exports `useKeyboardKeys`, `useRovingFocus`, and their public option, event, item, orientation, and return types. There are no documented subpath exports.
## SSR and production notes
These are React hooks and must be called at the top level of a React component or custom hook. `useKeyboardKeys` attaches browser listeners in an effect, so it does not access `window` or `document` during server rendering. In frameworks that distinguish server and client modules, call either hook from a client component; `useRovingFocus` carries a client directive. Keep the rendered item order and initial active item consistent between server and client for predictable hydration.
## Keyboard Keys
Source: https://puzzle-ui.com/docs/hooks/use-keyboard-keys
Listen for selected global keyboard events with configurable callbacks and event control.
`useKeyboardKeys` subscribes to selected key presses and releases on `window`. It is useful for shortcuts that should work regardless of which element currently has focus.
## Quick start
```tsx
import { useKeyboardKeys } from "@puzzle-ui/hooks";
function SearchShortcut({ openSearch }: { openSearch: () => void }) {
useKeyboardKeys({
keys: ["k"],
onKeyDown: (event) => {
if ((event.metaKey || event.ctrlKey) && !event.repeat) {
openSearch();
}
},
});
return null;
}
```
The hook listens during the capture phase. It normalizes key matching to lowercase and treats `Space` and `Spacebar` as aliases for the space character. The callback's `key` remains the browser's original `KeyboardEvent.key` value.
## API
```ts
useKeyboardKeys(options: UseKeyboardKeysOptions): void
```
| Option | Type | Default | Description |
| ----------------- | --------------------------------------- | ----------- | ---------------------------------------------------------------------------------------------------------- |
| `keys` | `readonly string[]` | Required | Keys to match, case-insensitively. Provide `KeyboardEvent.key` values such as `"Escape"`, `"k"`, or `" "`. |
| `onKeyDown` | `(event: UseKeyboardKeysEvent) => void` | `undefined` | Called for matching keydown events. |
| `onKeyUp` | `(event: UseKeyboardKeysEvent) => void` | `undefined` | Called for matching keyup events. |
| `preventDefault` | `boolean` | `false` | Calls `preventDefault()` for a matching event with a callback, when the event is cancelable. |
| `stopPropagation` | `boolean` | `false` | Calls `stopPropagation()` for a matching event with a callback. |
| `enabled` | `boolean` | `true` | When false, no listeners are active. |
The hook returns `void`. It installs listeners only when enabled and at least one callback is provided, and cleans them up when dependencies change or the component unmounts. It clears tracked modifier state when the window blurs or the document becomes hidden.
### Callback event
`UseKeyboardKeysEvent` contains the following fields:
| Field | Type | Description |
| ------------- | ------------------------ | ----------------------------------------------------- |
| `key` | `string` | The original key value from the browser event. |
| `type` | `"keydown"` or `"keyup"` | Which event triggered the callback. |
| `shiftKey` | `boolean` | Whether Shift is pressed for this event. |
| `ctrlKey` | `boolean` | Whether Control is pressed for this event. |
| `metaKey` | `boolean` | Whether Meta is pressed for this event. |
| `altKey` | `boolean` | Whether Alt is pressed for this event. |
| `repeat` | `boolean` | Whether the browser marks this as a repeated keydown. |
| `nativeEvent` | `KeyboardEvent` | The original browser event. |
## Usage notes
Because the listener is attached to `window`, it also observes matching keys while focus is in text fields and editable content. Check the target or application state in your callback when a shortcut should not run in those contexts. Modifier keys are reported on the event; include the main key in `keys` and check its modifier fields in the callback to define a chord.
## SSR
The hook registers `window` and `document` listeners inside `useEffect`, so those globals are not read during server rendering. In frameworks with server/client component boundaries, call it in a client component; that client component can still be server-rendered. Call it as a normal React hook, not conditionally.
## Exports
Import `useKeyboardKeys`, `UseKeyboardKeysOptions`, and `UseKeyboardKeysEvent` from `@puzzle-ui/hooks`. `KeyboardEventType` is an internal source type and is not exported from the package entry point.
## Roving Focus
Source: https://puzzle-ui.com/docs/hooks/use-roving-focus
Manage a single tab stop and keyboard navigation for a composite group of focusable items.
`useRovingFocus` manages the active item in a group so that only one enabled item is in the tab order at a time. It provides ref, focus, and keyboard handlers for implementing accessible menus, tabs, toolbars, and similar composite widgets.
## Quick start
```tsx
import { useRovingFocus, type RovingFocusItem } from "@puzzle-ui/hooks";
const items: RovingFocusItem[] = [
{ id: "overview" },
{ id: "activity" },
{ id: "settings", disabled: true },
];
function ProjectToolbar() {
const {
getItemRef,
getItemTabIndex,
onItemFocus,
onItemKeyDown,
} = useRovingFocus({
items,
orientation: "horizontal",
});
return (
{items.map((item) => (
))}
);
}
```
The hook only manages focus navigation; provide the appropriate widget roles, selection behavior, and activation logic for your component. Item IDs must be unique and stable across renders.
## API
```ts
useRovingFocus(
options: UseRovingFocusOptions,
): UseRovingFocusReturn
```
### Options
| Option | Type | Default | Description |
| ----------------- | ----------------------------------------- | ----------------------- | ------------------------------------------------------------------------------------------------ |
| `items` | `readonly RovingFocusItem[]` | Required | Current group items. Each item has a unique `id` and may have `disabled: true`. |
| `orientation` | `"horizontal"`, `"vertical"`, or `"both"` | `"horizontal"` | Which arrow keys move focus. Home and End work in every orientation. |
| `dir` | `"ltr"` or `"rtl"` | `"ltr"` | Reverses horizontal arrow-key direction in RTL. |
| `loop` | `boolean` | `true` | Whether moving past either end wraps to the other end. |
| `initialActiveId` | `string` | First enabled item's ID | Initial active item when it exists and is enabled. Otherwise the first enabled item is selected. |
### Return value
| Member | Type | Description |
| -------------------------------- | ----------------------------------------------------- | -------------------------------------------------------------------------------------------------------- |
| `activeId` | `string` or `undefined` | Active enabled item ID; undefined when no items are enabled. |
| `getItemRef(id)` | `RefCallback` | Ref callback that registers the item's element for programmatic focus. |
| `getItemTabIndex(id, disabled?)` | `0` or `-1` | Returns 0 for the active enabled item and -1 for other or disabled items. |
| `focusItem(id)` | `(id: string) => void` | Sets the active item and focuses its mounted element if it is enabled. |
| `onItemFocus(id)` | `(id: string) => void` | Updates the active item when an enabled item receives focus. |
| `onItemKeyDown(event, id)` | `(event: React.KeyboardEvent, id: string) => void` | Handles Home, End, and orientation-appropriate arrow keys. It leaves already-prevented events untouched. |
`RovingFocusItem`, `RovingFocusOrientation`, `UseRovingFocusOptions`, and `UseRovingFocusReturn` are also exported types.
## Keyboard behavior
* Horizontal groups use Left and Right; RTL reverses their direction.
* Vertical groups use Up and Down. `both` enables both pairs.
* Home moves to the first enabled item; End moves to the last.
* Disabled items are skipped. With looping enabled, navigation wraps; otherwise it stops at the group boundary.
* The hook calls `preventDefault()` only when it handles a supported key and focuses a valid next item.
## SSR and client components
This hook is marked with React's `"use client"` directive and uses state, effects, and element refs. In server/client framework setups, call it in a client component. Its initial active ID is derived from the supplied item list and `initialActiveId`; provide consistent initial items on the server and client to avoid hydration mismatches. Focus changes require mounted DOM elements.
## Exports
Import `useRovingFocus` and its public types from `@puzzle-ui/hooks`. The package does not expose a separate subpath for this hook.
## Icons
Source: https://puzzle-ui.com/docs/icons
Render Iconify icons as React SVG components and style them with CSS, currentColor, or Puzzle theme tokens.
`@puzzle-ui/icons` provides a React `Icon` component backed by Iconify. Pass an Iconify-prefixed icon name such as `lucide:house`; the package does not export each icon as a separate React component.
**API maturity: Stable.** The documented `Icon` component API is covered by tests and is intended to remain backward-compatible within a major version. This is an API commitment, not a guarantee of production readiness in every application.
## Install
#### npm
```bash
npm install @puzzle-ui/icons react@^19 react-dom@^19
```
#### bun
```bash
bun add @puzzle-ui/icons react@^19 react-dom@^19
```
#### pnpm
```bash
pnpm add @puzzle-ui/icons react@^19 react-dom@^19
```
#### yarn
```bash
yarn add @puzzle-ui/icons react@^19 react-dom@^19
```
React and React DOM `^19.0.0` are peer dependencies. If they are already installed in your app, you do not need to add them again.
## Quick start
```tsx
import { Icon } from "@puzzle-ui/icons";
export function HomeLink() {
return (
);
}
```
Icon names use Iconify's `prefix:name` format. `Icon` passes the name to Iconify at runtime; it is not a statically imported named icon. Iconify may request icon data over the network, so account for network availability and your Content Security Policy.
## Sizing and color
By default, the SVG uses `1em` for its width and height, so it follows the surrounding text size. Set `size` to a number of pixels, or use the standard SVG `width`, `height`, and `style` props for other dimensions. When `size` is supplied it takes precedence over width and height.
With no explicit `color`, the icon inherits the surrounding CSS text color (`currentColor`). You can set `color` directly or apply it through a parent or `style`. Use a semantic theme token to keep the icon aligned with the active Puzzle theme:
```tsx
```
The token resolves through the active `Theme` and adapts to its color scheme. Icons whose SVG paths specify their own fixed colors may not inherit `currentColor`. You do not need a Puzzle theme provider to use the icon package; CSS variables are simply a convenient option when your application already uses `@puzzle-ui/theme`.
## Accessibility
Treat icons as decorative when adjacent text already conveys the same meaning. Hide decorative SVGs from assistive technology with `aria-hidden="true"`:
```tsx
```
When an icon itself communicates information, give it an accessible name, for example with `role="img"` and `aria-label`. For icon-only controls, label the button or link rather than relying on a decorative icon to name its parent. The component forwards SVG attributes, including ARIA attributes, to the rendered SVG.
## API
```ts
Icon(props: IconProps): import("react").JSX.Element
```
| Prop | Type | Default | Description |
| -------------- | ------------------------------------------------------------- | ------------------------ | ---------------------------------------------------------------------------------------------------------------------- |
| `name` | `string` | Required | Iconify icon identifier in `prefix:name` form. |
| `size` | `number` | `undefined` | Width and height in pixels. Overrides `width` and `height`. |
| `color` | `string` | Inherited `currentColor` | CSS color applied to the icon. Accepts CSS values such as `var(--puzzle-color-primary)`. |
| `showLoader` | `boolean` | `false` | Renders an animated loading indicator in place of the icon. Animation is disabled for users who prefer reduced motion. |
| SVG attributes | `ComponentProps<"svg">` except `mode`, `onLoad`, and `rotate` | — | Standard SVG properties such as `width`, `height`, `className`, `style`, `role`, and `aria-*` are forwarded. |
`IconProps` is exported as a type. The package root `@puzzle-ui/icons` is the only public entry point; generated icon-set files are not package subpaths.
## SSR and production notes
The component can be included in server-rendered React applications, but Iconify may load requested icon data asynchronously in the browser. Ensure the icon set is available under your network and Content Security Policy rules, or use a controlled asset strategy appropriate to your deployment. `showLoader` provides a visual loading indicator; it is not a substitute for an accessible status message when loading state matters to users.
For theme-aware colors, see [Design tokens](https://puzzle-ui.com/docs/theme/tokens). For labeled
actions that contain decorative icons, use the [Button component](https://puzzle-ui.com/docs/ui/actions/button).
## Exports
The package root exports `Icon` and the `IconProps` type. It supports ESM, CommonJS, and TypeScript declarations. Individual icon collection files under the source tree are not public exports.
## Puzzle Authentication Observability
Source: https://puzzle-ui.com/docs/observability
Monitoring, metrics, health checks, and operational requirements for production authentication deployments.
This document describes the recommended monitoring and operational
requirements for production authentication deployments.
## Health checks
Use two separate health concepts.
### Liveness
Liveness determines whether the application process is running.
It should not depend on database availability.
A temporary database outage should not automatically restart every
application instance.
### Readiness
Readiness determines whether an instance can safely serve authentication
requests.
Use the server-side createAuthReadinessHandler from
@puzzle-ui/fullstack/auth/server.
Recommended checks:
* Database connectivity.
* Required authentication collections.
* Session storage availability.
* Migration readiness.
* Shared rate-limit storage availability.
Readiness checks should have bounded execution times.
Do not expose provider exceptions or infrastructure details through
public health endpoints.
## Structured logging
Use structured JSON logs.
Recommended fields:
* timestamp
* level
* service
* environment
* requestId
* operation
* outcome
* durationMs
* errorCode
* storageAdapter
Do not include credentials or raw user identifiers.
Never log:
* Session tokens.
* MFA challenge tokens.
* Password reset tokens.
* Email verification tokens.
* Passwords.
* Password hashes.
* TOTP secrets.
* Recovery codes.
* WebAuthn private material.
* Database connection strings.
Authentication failures should use stable error codes rather than exposing
provider-specific exceptions.
## Recommended metrics
### Authentication
* auth_requests_total
* auth_request_duration_seconds
* auth_sign_in_failures_total
* auth_registration_total
* auth_password_reset_requests_total
* auth_email_verification_total
### MFA
* auth_mfa_challenges_total
* auth_mfa_verifications_total
* auth_mfa_failures_total
* auth_mfa_recovery_code_usage_total
* auth_passkey_verifications_total
### Sessions
* auth_session_creations_total
* auth_session_rotations_total
* auth_session_revocations_total
* auth_session_validation_failures_total
### Storage
* auth_storage_operations_total
* auth_storage_operation_duration_seconds
* auth_storage_errors_total
* auth_storage_conflicts_total
### Rate limiting
* auth_rate_limit_allowed_total
* auth_rate_limit_rejected_total
* auth_rate_limit_storage_errors_total
Use bounded labels such as:
* operation
* adapter
* outcome
* authentication method
* error code
Never use email addresses, session IDs, tokens, IP addresses or user IDs as
metric labels.
Avoid unbounded cardinality.
## Performance monitoring
Measure at least:
* Registration latency.
* Password sign-in latency.
* MFA verification latency.
* Passkey verification latency.
* Session validation latency.
* Session rotation latency.
* Recovery-code verification latency.
* Storage query latency.
* Rate-limit latency.
Record p50, p95 and p99 latency.
### Argon2id
Benchmark the actual production password hashing provider.
Measure:
* CPU time.
* Memory consumption.
* Concurrent hash operations.
* Authentication latency under load.
* Resource exhaustion behavior.
Choose Argon2id parameters according to the production runtime and available
resources.
Do not assume parameters suitable for a Node.js server are automatically
suitable for Cloudflare Workers.
### MongoDB
Monitor:
* Connection pool utilization.
* Connection wait time.
* Transaction duration.
* Transaction failures.
* Query latency.
* Conditional-write conflicts.
### Cloudflare D1
Monitor:
* Query latency.
* Transaction duration.
* Database errors.
* Worker CPU time.
* Worker memory usage.
* D1 limits and throttling.
### Session load
Test:
* Concurrent session creation.
* Session validation under load.
* Concurrent rotation.
* Revocation of multiple sessions.
* Expiration cleanup.
### Rate limiting
Run the local concurrency benchmark:
bun run benchmark:auth
This benchmark uses MemoryStorage and is intended for regression comparisons.
Production capacity measurements must use the actual MongoDB or D1 adapter.
## Fault injection
Production-readiness testing should include:
* Database connection loss.
* Database write failures.
* Conditional-write conflicts.
* Transaction failures.
* Rate-limit provider failure.
* Email provider failure.
* Session provider failure.
* WebAuthn provider errors.
Verify that:
* Authentication fails closed when required security dependencies fail.
* Failed writes do not partially commit security-critical operations.
* Consumed challenges cannot be restored.
* Recovery codes cannot be reused.
* Failed initialization can be retried.
* Existing sessions are not incorrectly authorized after security failures.
## Alerting
Recommended alerts:
* Elevated authentication failure rate.
* Elevated HTTP 5xx rate on auth routes.
* Database connection failures.
* Increased transaction conflicts.
* Rate-limit storage failures.
* Unusual recovery-code usage.
* Repeated WebAuthn verification failures.
* Unexpected session revocation spikes.
* Increased p95 authentication latency.
Alerts must not contain secrets or personal authentication data.
## Operational dashboards
Maintain separate dashboards for:
1. Authentication availability.
2. Authentication latency.
3. MFA security events.
4. Session activity.
5. Database performance.
6. Rate-limit behavior.
7. Infrastructure resource usage.
Use the same service and environment identifiers across logs, traces and
metrics.
## Production acceptance
Before production approval:
* Verify liveness and readiness endpoints.
* Verify that readiness becomes unavailable when storage fails.
* Verify that liveness remains independent of storage.
* Confirm that metrics have bounded cardinality.
* Confirm that sensitive information is absent from logs.
* Record performance baselines for the actual production adapters.
* Test recovery after transient provider failures.
## React Page Sections
Source: https://puzzle-ui.com/docs/pieces
Compose responsive marketing sections and introductory page heroes with @puzzle-ui/pieces.
`@puzzle-ui/pieces` provides composed interface sections built on Puzzle UI. Use the existing Hero layouts for page introductions and the Marketing & Conversion collection for product features, customer proof, FAQs, comparisons, and calls to action. Pieces is not a general-purpose page builder or a library of complete website templates.
## Start with a Hero
Import the generic `Hero` component when you want to provide your own content and actions. The API also includes layout and visual presets such as `SplitHero`, `CenteredHero`, `ProductHero`, and `CampaignHero`.
```tsx
import { Button } from "@puzzle-ui/ui";
import { Hero } from "@puzzle-ui/pieces";
export function ProductIntroduction() {
return (
Get started}
/>
);
}
```
The generic component supports different layouts, content alignment, and optional media. Browse the [Hero reference](https://puzzle-ui.com/docs/pieces/components/hero) for available layouts, presets, and examples.
## Compose, do not replace
Pieces supplies larger sections, while [`@puzzle-ui/ui`](https://puzzle-ui.com/docs/ui) provides the underlying components and [`@puzzle-ui/theme`](https://puzzle-ui.com/docs/theme) provides design tokens and theme behavior. You can use a Hero on a page and compose the rest of the interface from those building blocks.
## Marketing & Conversion
Ten new section families cover announcements, logos, features, benefits,
statistics, testimonials, calls to action, FAQs, process steps, and
comparisons. Browse the [Marketing & Conversion overview](https://puzzle-ui.com/docs/pieces/components/marketing)
for the catalog and shared design principles.
## API maturity
The documented Hero component and presets have **Stable** APIs, with
backward-compatibility intent within a major version. This describes API
maturity, not production readiness. Check the
[Hero API reference](https://puzzle-ui.com/docs/pieces/components/hero) for supported props and
review the [API maturity guide](https://puzzle-ui.com/docs/tutorials#api-maturity).
## AnnouncementSection
Source: https://puzzle-ui.com/docs/pieces/components/announcement
Present announcements, promotions, countdowns, and multiple dismissible notices with accessible controls.
`AnnouncementSection` displays a concise notice with optional icon and consumer-provided action. It supports a single message, a countdown, or independently dismissible messages. It does not own campaign routing, persistence, or scheduling.
**API maturity: Beta.**
## Installation
```tsx
import { AnnouncementSection } from "@puzzle-ui/pieces";
```
## Variant previews
Every supported variant has an individual runnable preview. The dismiss control is keyboard operable; countdown mode requires a valid date string or `Date`.
## API
| Prop | Type | Description |
| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- |
| `variant` | `"bar" \| "dismissible" \| "centered" \| "split" \| "promotional" \| "countdown" \| "ticker" \| "multi-message" \| "floating" \| "minimal"` | Selects the presentation. Defaults to `bar`. |
| `message` | `ReactNode` | Content for a single announcement. |
| `icon` | `ReactNode` | Optional decorative icon for a single announcement. |
| `action` | `ReactNode` | Consumer-provided action for a single announcement. |
| `dismissible` | `boolean` | Enables the dismiss button. Defaults to true for the `dismissible` variant. |
| `dismissLabel` | `string` | Accessible name for the dismiss button. |
| `countdownTarget` | `Date \| string` | Required with `variant="countdown"`; invalid dates throw a `RangeError`. |
| `announcements` | `readonly AnnouncementItem[]` | Required with `variant="multi-message"`; each item needs a stable `id` and `message`. |
| Shared section props | `SectionRootProps` and heading props | Semantic root, theme, native attributes, optional heading, actions, and children. |
## Usage
```tsx
Explore the collection}
/>
```
`multi-message` accepts `icon`, `action`, and `dismissLabel` per announcement item. Dismissed messages are removed for the current mounted instance; persistence is the consumer's responsibility. The `ticker` layout is horizontally scrollable and does not animate automatically.
## Accessibility
Dismiss controls are real buttons with an accessible name and normal keyboard behavior. Use meaningful action text, keep notice content concise, and do not place essential information only in a decorative icon. A countdown is exposed as a `time` element; it is not announced every second.
## BenefitsSection
Source: https://puzzle-ui.com/docs/pieces/components/benefits
Communicate customer outcomes with responsive benefit lists, cards, icons, media, and featured content.
`BenefitsSection` focuses on outcomes rather than feature details. Each item has a stable ID and title, with optional description, icon, media, action, or featured emphasis.
**API maturity: Beta.**
## Installation
```tsx
import { BenefitsSection, type BenefitItem } from "@puzzle-ui/pieces";
```
## Variant previews
The collection adapts from a single column on narrow screens to wider grid layouts when there is room.
## API
| Prop | Type | Description |
| ---------------------- | ------------------------------------ | ------------------------------------------------------------------------ |
| `variant` | `BenefitsVariant` | Selects one of twelve benefit compositions; defaults to `grid`. |
| `items` | `readonly BenefitItem[]` | Benefit content with stable `id`, required `title`, and optional slots. |
| `BenefitItem.icon` | `ReactNode` | Optional consumer-provided icon. |
| `BenefitItem.media` | `ReactNode` | Optional media node. |
| `BenefitItem.action` | `ReactNode` | Consumer-provided action. |
| `BenefitItem.featured` | `boolean` | Emphasizes the item in supported variants. |
| Shared section props | `SectionRootProps` and heading props | Semantic root, theme, native attributes, heading, actions, and children. |
## Usage
```tsx
```
The section does not imply product-specific claims or generate content. Empty collections omit the list while preserving optional heading content.
## Accessibility
Use descriptive titles and provide text alternatives through the consumer-provided media. Keep icon-only meaning in the item's text as well.
## ComparisonSection
Source: https://puzzle-ui.com/docs/pieces/components/comparison
Compare plans, products, or options with responsive cards or an accessible, keyboard-scrollable feature table.
`ComparisonSection` compares consumer-provided options and feature values. Each option has a stable ID and title; each feature has an ID, label, and values keyed by option ID.
**API maturity: Beta.**
## Installation
```tsx
import {
ComparisonSection,
type ComparisonFeature,
type ComparisonOption,
} from "@puzzle-ui/pieces";
```
## Variant previews
Table variants use semantic row/column headers and boolean values are labeled as included or not included. The interactive variant exposes a native radio group. On narrow screens the table scrolls within a labeled, keyboard-focusable viewport rather than widening the page.
## API
| Prop | Type | Description |
| ------------------------- | ------------------------------------ | ---------------------------------------------------------------------------- |
| `variant` | `ComparisonVariant` | Selects one of twelve comparison compositions; defaults to `table`. |
| `options` | `readonly ComparisonOption[]` | Options with stable `id`, required `title`, and optional description/action. |
| `features` | `readonly ComparisonFeature[]` | Rows with stable `id`, label, and a `values` record keyed by option ID. |
| `highlightedOptionId` | `string` | Option emphasized in supported layouts. |
| `comparisonLabel` | `string` | Accessible label for the table viewport and table caption. |
| `selectedOptionId` | `string` | Controlled selection for `variant="interactive"`. |
| `defaultSelectedOptionId` | `string` | Initial uncontrolled selection for `variant="interactive"`. |
| `onSelectionChange` | `(optionId: string) => void` | Selection callback for `variant="interactive"`. |
| Shared section props | `SectionRootProps` and heading props | Semantic root, theme, native attributes, heading, actions, and children. |
Feature values may be booleans, strings, numbers, or React nodes. Undefined values render as `Not provided`. Selection state remains local unless controlled; no pricing or billing logic is included.
## Usage
```tsx
```
An empty option collection omits the comparison structure. Use unique option and feature IDs, and ensure each feature's value keys match the option IDs.
## Accessibility
Tables include a caption, column headers, and row headers. Interactive table options use native radio controls. The scroll viewport is keyboard focusable and labeled so users can reach off-screen columns without page-level horizontal overflow.
## CTASection
Source: https://puzzle-ui.com/docs/pieces/components/cta
Invite visitors to a consumer-defined next step with responsive call-to-action layouts and optional media.
`CTASection` composes a message, optional media, actions, and custom children. It does not implement a newsletter form, download, trial, contact flow, or application behavior; consumers provide those elements.
**API maturity: Beta.**
## Installation
```tsx
import { CTASection } from "@puzzle-ui/pieces";
```
## Variant previews
Each preview shares the same typed content slots while applying its named composition. Theme and background behavior inherit from the shared UI section props.
## API
| Prop | Type | Description |
| ----------------------------------- | ------------------ | ---------------------------------------------------------------------------- |
| `variant` | `CTAVariant` | Selects one of sixteen call-to-action presentations; defaults to `centered`. |
| `title` / `description` / `eyebrow` | `ReactNode` | Shared section heading content. |
| `primaryAction` / `secondaryAction` | `ReactNode` | Consumer-provided next steps. |
| `media` | `ReactNode` | Optional consumer-provided media. |
| `children` | `ReactNode` | Additional composable content such as a form. |
| Shared section props | `SectionRootProps` | Semantic root, theme, native attributes, width, and spacing. |
## Usage
```tsx
Start a trial}
secondaryAction={Read the guide}
/>
```
The action slots are omitted when not supplied. Provide links, buttons, forms, and their loading/error behavior from the consuming application.
## Accessibility
Use descriptive action names and maintain a logical heading level. If a form is passed through `children`, provide its own labels, validation messages, and submission feedback.
## Dashboard Components
Source: https://puzzle-ui.com/docs/pieces/components/dashboard
Compose accessible dashboard headers, statistics, activity feeds, progress cards, and layouts with Puzzle Pieces.
Dashboard compositions provide reusable structure for product and admin interfaces without coupling presentation to a router, data model, or framework.
**API maturity: Beta.** These compositions are new and may evolve based on feedback.
## Installation
Import the dashboard components from Puzzle Pieces:
```tsx
import {
DashboardActivityFeed,
DashboardHeader,
DashboardProgressCard,
DashboardShell,
DashboardStatCard,
DashboardStatGroup,
} from "@puzzle-ui/pieces";
```
## Dashboard header
Use the header for the page title, supporting text, and caller-provided actions.
## Statistics
`DashboardStatGroup` arranges any children into a responsive grid. Compose it with `DashboardStatCard`; the card supports an icon, trend, description, action slot, and loading state.
## Activity feed
Activity items are generic records supplied by the consuming application. Use `renderItem` when an item needs a custom presentation; otherwise the component renders optional avatars, links, and semantic timestamps.
## Progress card
Use a native progress element with a title-derived accessible label.
## Dashboard shell
`DashboardShell` composes caller-provided topbar, sidebar, and page content. Navigation and routing remain the responsibility of the application.
```tsx
}
sidebar={}
sidebarLabel="Workspace navigation"
>
{/* cards */}
```
## Accessibility and responsive behavior
* The header uses a level-one heading; place only one `DashboardHeader` on a page.
* `DashboardStatGroup` is a labelled region. Cards expose their labels as headings.
* Loading cards expose `aria-busy` and hide decorative placeholders from assistive technology.
* Activity feeds use an ordered list and native `