SDK API Reference
Functions
Section titled “Functions”init(config)
Section titled “init(config)”Initializes the SDK, loads or creates an anonymous ID, queues the initial pageview, and starts the event flush timer.
checkAccess(url?)
Section titled “checkAccess(url?)”Calls GET /api/v1/access/check with the URL, userId, and anonymousId.
- if denied and
onPaywallis set, the callback runs - if denied and
onPaywallis not set, the built-in paywall is shown - on error, the SDK returns
{ granted: true, reason: 'error_fallback' }
identify(userId)
Section titled “identify(userId)”Sets the current userId for future access checks and events.
resetIdentity()
Section titled “resetIdentity()”Clears userId and falls back to the browser’s stored anonymous ID.
trackEvent(eventType, properties?)
Section titled “trackEvent(eventType, properties?)”Queues a custom event for batched delivery.
trackPageview(properties?)
Section titled “trackPageview(properties?)”Queues a pageview event and automatically includes url, path, title, and referrer.
showPaywall(result)
Section titled “showPaywall(result)”Renders the built-in paywall UI for a supplied access result.
hidePaywall()
Section titled “hidePaywall()”Removes the built-in paywall from the DOM.
getConfig()
Section titled “getConfig()”Returns the current SDK config or null before initialization.
Auth Functions
Section titled “Auth Functions”register(email, password, name?)
Section titled “register(email, password, name?)”Register a new customer. Stores tokens in localStorage and fires auth change listeners. Returns an AuthResult.
login(email, password)
Section titled “login(email, password)”Log in an existing customer. Stores tokens in localStorage and fires auth change listeners. Returns an AuthResult.
logout()
Section titled “logout()”Revoke the refresh token on the server and clear all stored tokens. Fires auth change listeners with null.
getSession()
Section titled “getSession()”Get the current customer’s profile from the server. Automatically refreshes the access token if expired. Returns CustomerProfile | null.
isAuthenticated()
Section titled “isAuthenticated()”Check if the customer has stored tokens (synchronous, no network request). Returns boolean.
getStoredCustomer()
Section titled “getStoredCustomer()”Get the stored customer info from localStorage without a network request. Returns AuthCustomer | null.
getValidAccessToken()
Section titled “getValidAccessToken()”Get a valid access token, refreshing if necessary. Used internally by checkAccess(). Returns string | null.
onAuthChange(callback)
Section titled “onAuthChange(callback)”Register a callback that fires whenever the auth state changes (login, logout, token refresh). Returns an unsubscribe function.
const unsubscribe = onAuthChange((customer) => { if (customer) { console.log('Logged in as', customer.email); } else { console.log('Logged out'); }});Billing Functions
Section titled “Billing Functions”checkout(options)
Section titled “checkout(options)”Create a Stripe Checkout session and redirect the browser. Requires the customer to be logged in. Uses the JWT Bearer token with a pk_ key.
await checkout({ priceId: 'latch-price-uuid', successUrl: 'https://yoursite.com/welcome', cancelUrl: 'https://yoursite.com/pricing',});Options: priceId (required), successUrl (optional), cancelUrl (optional). Returns CheckoutResult.
openPortal(options?)
Section titled “openPortal(options?)”Open the Stripe Customer Portal for subscription self-service. Requires the customer to be logged in and have a Stripe customer record.
await openPortal({ returnUrl: 'https://yoursite.com/account' });Options: returnUrl (optional, defaults to current page). Returns PortalResult.
getSubscription()
Section titled “getSubscription()”Get the current customer’s active subscription. Returns SubscriptionInfo | null.
const sub = await getSubscription();if (sub) console.log(sub.status, sub.currentPeriodEnd);LatchConfig
Section titled “LatchConfig”interface LatchConfig { apiKey: string; apiUrl?: string; userId?: string; anonymousId?: string; onPaywall?: (result: AccessResult) => void; onCheckout?: (productIds: string[]) => void; paywallSelector?: string; debug?: boolean;}| Field | Description |
|---|---|
apiKey | Publishable key |
apiUrl | API base URL |
userId | Known reader ID |
anonymousId | Override the browser-stored anonymous ID |
onPaywall | Custom denied-access handler |
onCheckout | Built-in Subscribe-button handler |
paywallSelector | Target for inline paywalls |
debug | Enables console logs |
AccessResult
Section titled “AccessResult”interface AccessResult { granted: boolean; reason?: string; paywallRule?: { id: string; type: string; action: { productIds: string[]; message?: string; meterLimit?: number; template?: string; }; }; meterRemaining?: number;}Current reason values returned by the implementation are subscribed, free_content, metered_remaining, registered, and error_fallback.
AuthResult
Section titled “AuthResult”interface AuthResult { accessToken: string; refreshToken: string; expiresAt: number; customer: AuthCustomer;}AuthCustomer
Section titled “AuthCustomer”interface AuthCustomer { id: string; email: string; name: string | null;}CustomerProfile
Section titled “CustomerProfile”interface CustomerProfile { id: string; email: string; name: string | null; customAttributes: Record<string, unknown>; createdAt: string;}CheckoutOptions
Section titled “CheckoutOptions”interface CheckoutOptions { priceId: string; successUrl?: string; cancelUrl?: string;}CheckoutResult
Section titled “CheckoutResult”interface CheckoutResult { sessionId: string; url: string;}PortalResult
Section titled “PortalResult”interface PortalResult { url: string;}SubscriptionInfo
Section titled “SubscriptionInfo”interface SubscriptionInfo { id: string; priceId: string; status: string; cancelAtPeriodEnd: boolean; currentPeriodStart: string | null; currentPeriodEnd: string | null; cancelledAt: string | null; createdAt: string;}