stacks-browser

$npx mdskill add stacksjs/stacks/stacks-browser

Provides browser utilities for auth, billing, API calls, and model loading in Stacks.

  • Handles user login, registration, logout, and token management via useAuth composable.
  • Depends on Stripe for billing and a custom Fetch client for API requests.
  • Recommends actions based on authentication state and user input.
  • Returns composable functions and utilities for direct use in frontend code.

SKILL.md

.github/skills/stacks-browserView on GitHub ↗
---
name: stacks-browser
description: Use when working with browser/frontend functionality in Stacks — the useAuth composable (login, register, logout, token management), Stripe billing utilities (loadCardElement, confirmPayment), the API fetch client, browser model loading, or auto-imported browser utilities. Covers @stacksjs/browser.
license: MIT
compatibility: Bun >= 1.3.0, TypeScript
allowed-tools: Read Edit Write Bash Grep Glob
---

# Stacks Browser

Frontend/browser utilities for STX applications.

## Key Paths
- Core package: `storage/framework/core/browser/src/`
- Auto-imports: `storage/framework/browser-auto-imports.json`

## Authentication Composable (useAuth)

```typescript
const { user, isAuthenticated, login, register, logout, token, errors, loading } = useAuth()

// Login
await login({ email: '[email protected]', password: 'secret' })

// Register
await register({ email: '[email protected]', password: 'secret', name: 'John' })

// Logout
await logout()

// Auth guard (redirect if not authenticated)
authGuard()              // redirect to /login
authGuard({ guest: true })  // redirect if authenticated (for login page)
```

## API Client (Fetch)

```typescript
import { Fetch, initApi } from '@stacksjs/browser'

initApi({ baseUrl: '/api', onUnauthorized: () => router.push('/login') })

const users = await Fetch.get('/users')
await Fetch.post('/users', { name: 'John' })
await Fetch.patch('/users/1', { name: 'Jane' })
await Fetch.put('/users/1', data)
await Fetch.destroy('/users/1')
Fetch.setToken('bearer-token')
```

## Stripe Billing (Browser-Side)

```typescript
import { loadCardElement, loadPaymentElement, confirmCardSetup, confirmCardPayment, confirmPayment, createPaymentMethod } from '@stacksjs/browser'

// Load Stripe Elements
const cardElement = await loadCardElement(clientSecret)
const paymentElement = await loadPaymentElement(clientSecret)

// Confirm payment
const { paymentIntent, error } = await confirmCardPayment(clientSecret, elements)
const { setupIntent, error } = await confirmCardSetup(clientSecret, elements)
const { paymentIntent, error } = await confirmPayment(elements)
const { paymentIntent, error } = await createPaymentMethod(elements)
```

## Browser Model Loading

```typescript
import { loadBrowserModels, getBrowserModel, getBrowserModelNames } from '@stacksjs/browser'

await loadBrowserModels()               // loads all models from app/Models/
const User = getBrowserModel('User')
const names = getBrowserModelNames()     // ['User', 'Post', ...]
```

## Browser Query Builder

```typescript
import { browserQuery, BrowserQueryBuilder, browserAuth, createBrowserModel, createBrowserDb } from '@stacksjs/browser'

const users = await browserQuery('users').where('active', true).get()
const db = createBrowserDb({ baseUrl: '/api' })
```

## Utility Functions

```typescript
// Date
useDateFormat(date, 'YYYY-MM-DD')
useNow()

// Formatting
formatAreaSize(sqMeters)       // '1,234 sq ft' or 'X acres'
formatDistance(miles)           // '1.5 mi' or '2,640 ft'
formatElevation(feet)          // '1,234 ft'
formatDuration(seconds)        // '2h 15m'
getRelativeTime(dateString)    // '5 minutes ago'

// Async
fetchData(fetcher, { onError, fallback })

// Random
random(size?)                  // nanoid
customAlphabet(alphabet, size) // custom nanoid

// Regex (magic-regexp)
createRegExp(pattern)

// Retry
retry(fn, { retries: 3, initialDelay: 100, backoffFactor: 2 })

// Sleep
sleep(ms), wait(ms), delay(ms)
waitUntil(condition, { interval, timeout })
waitWhile(condition, options)

// Promise
createSingletonPromise(fn)
createControlledPromise()
createPromiseLock()
```

## Guards
- `notNullish(v)` — type guard for non-null/undefined
- `noNull(v)` — excludes null
- `notUndefined(v)` — excludes undefined
- `isTruthy(v)` — excludes falsy values

## Auto-Initialization
```typescript
autoInit()  // initializes all browser utilities, exposes on window.StacksBrowser
```

## Re-exports from Composables
`useDark`, `useFetch`, `useOnline`, `useStorage`, `useToggle`, `useDateFormat`, `useNow`, `usePreferredDark`

## Gotchas
- All browser utilities are auto-imported in STX templates
- `initApi()` must be called before using `Fetch`
- `loadCardElement()` requires Stripe.js to be loaded
- `publishableKey` must be set for Stripe integration
- Browser models use a different query builder than server-side models
- `autoInit()` exposes utilities on `window.StacksBrowser`
- Do NOT use `document.*`, `window.*` directly in STX templates

More from stacksjs/stacks

SkillDescription
stacks-actionsUse when working with Stacks server actions — creating actions in app/Actions/, auto-generated API actions from the useApi model trait, the 80+ default framework actions (auth, dashboard, commerce, content, deployment, jobs), action request/response handling, or action registration. Covers @stacksjs/actions and storage/framework/defaults/actions/.
stacks-aiUse when integrating AI capabilities into a Stacks application — using Anthropic/OpenAI/Ollama/AWS Bedrock drivers, image generation (DALL-E), vision analysis, RAG/vector search, embeddings, MCP (Model Context Protocol) clients, text summarization, sentiment analysis, content classification, personalization, or the buddy AI assistant. Covers @stacksjs/ai and config/ai.ts.
stacks-aliasUse when working with path aliases in a Stacks project — import resolution, module aliasing, or debugging import paths. Covers @stacksjs/alias which defines 260+ path mappings for the entire framework.
stacks-analyticsUse when adding analytics to a Stacks application — configuring Fathom or self-hosted analytics, generating tracking scripts, privacy-friendly analytics setup, or the analytics configuration. Covers @stacksjs/analytics and config/analytics.ts.
stacks-apiUse when building, modifying, or debugging API endpoints in a Stacks application — defining routes, handling requests, API middleware, working with the API server, HTTP client (fetcher), API resources, or OpenAPI generation. Covers both @stacksjs/api utilities and the stacks-api server implementation.
stacks-arraysUse when working with array utilities in Stacks — statistical operations (average, median, mode, standard deviation, z-score, percentile, covariance), array manipulation (unique, flatten, partition, shuffle, sample, move), containment checks, or the Arr facade. Covers @stacksjs/arrays.
stacks-authUse when implementing authentication, authorization, passkeys, TOTP/2FA, RBAC, gates, policies, session auth, token management, email verification, password resets, or rate limiting in a Stacks application. Covers the @stacksjs/auth package, config/auth.ts, app/Gates.ts, and app/Middleware/.
stacks-auto-importsUse when working with the Stacks auto-import system — understanding how browser and server auto-imports work, configuring auto-imported functions/models/composables, the auto-import manifests, type generation, or how globals are injected. Covers the auto-import pipeline at storage/framework/auto-imports/.
stacks-brandkitUse when defining or exploring a brand identity for a Stacks project and you want premium brand-kit REFERENCE IMAGES first - logo directions, palettes, typography specimens, identity boards, and application/mockup decks. Generates IMAGES ONLY, never code. Trained for minimalist, cinematic, editorial, dark-tech, luxury, cultural, security, gaming, developer-tool, and consumer-app brand systems with intentional logo concepting, sparse type, strong symbolic meaning, and disciplined palettes a coding step can build against.
stacks-browseUse for headless browser QA on Stacks applications — navigation, screenshots, responsive testing, console/network monitoring, and accessibility snapshots. Dependency-free: drives a system browser over the Chrome DevTools Protocol using only Bun (no Playwright/Puppeteer). Invoke with /stacks-browse.