usebecky 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/README.md +701 -2
  2. package/dist/analytics/client.d.ts +219 -0
  3. package/dist/analytics/client.js +923 -0
  4. package/dist/analytics/cmp.d.ts +20 -0
  5. package/dist/analytics/cmp.js +166 -0
  6. package/dist/analytics/context.d.ts +29 -0
  7. package/dist/analytics/context.js +97 -0
  8. package/dist/auth/client.d.ts +401 -0
  9. package/dist/auth/client.js +1081 -0
  10. package/dist/auth/webauthn.d.ts +18 -0
  11. package/dist/auth/webauthn.js +138 -0
  12. package/dist/cli/ai.d.ts +54 -0
  13. package/dist/cli/ai.js +202 -0
  14. package/dist/cli/analytics.d.ts +53 -0
  15. package/dist/cli/analytics.js +357 -0
  16. package/dist/cli/config.d.ts +75 -0
  17. package/dist/cli/config.js +718 -0
  18. package/dist/cli/db.d.ts +48 -0
  19. package/dist/cli/db.js +215 -0
  20. package/dist/cli/deploy-api.d.ts +168 -0
  21. package/dist/cli/deploy-api.js +177 -0
  22. package/dist/cli/deploy-ci.d.ts +15 -0
  23. package/dist/cli/deploy-ci.js +54 -0
  24. package/dist/cli/deploy-detect.d.ts +64 -0
  25. package/dist/cli/deploy-detect.js +249 -0
  26. package/dist/cli/deploy-files.d.ts +112 -0
  27. package/dist/cli/deploy-files.js +778 -0
  28. package/dist/cli/deploy.d.ts +10 -0
  29. package/dist/cli/deploy.js +430 -0
  30. package/dist/cli/emails.d.ts +29 -0
  31. package/dist/cli/emails.js +122 -0
  32. package/dist/cli/framework.d.ts +135 -0
  33. package/dist/cli/framework.js +459 -0
  34. package/dist/cli/functions.d.ts +59 -0
  35. package/dist/cli/functions.js +426 -0
  36. package/dist/cli/hosting.d.ts +4 -0
  37. package/dist/cli/hosting.js +532 -0
  38. package/dist/cli/index.d.ts +2 -0
  39. package/dist/cli/index.js +9 -0
  40. package/dist/cli/payments.d.ts +35 -0
  41. package/dist/cli/payments.js +176 -0
  42. package/dist/cli/push.d.ts +36 -0
  43. package/dist/cli/push.js +172 -0
  44. package/dist/cli/run.d.ts +65 -0
  45. package/dist/cli/run.js +850 -0
  46. package/dist/cli/social.d.ts +52 -0
  47. package/dist/cli/social.js +532 -0
  48. package/dist/cli/tokens.d.ts +28 -0
  49. package/dist/cli/tokens.js +114 -0
  50. package/dist/cli/ui.d.ts +38 -0
  51. package/dist/cli/ui.js +140 -0
  52. package/dist/client.d.ts +94 -0
  53. package/dist/client.js +156 -0
  54. package/dist/db/query.d.ts +162 -0
  55. package/dist/db/query.js +336 -0
  56. package/dist/db/types.d.ts +93 -0
  57. package/dist/db/types.js +4 -0
  58. package/dist/forms/client.d.ts +65 -0
  59. package/dist/forms/client.js +106 -0
  60. package/dist/functions/client.d.ts +37 -0
  61. package/dist/functions/client.js +76 -0
  62. package/dist/index.d.ts +17 -0
  63. package/dist/index.js +16 -0
  64. package/dist/lib/dashboard-paths.d.ts +4 -0
  65. package/dist/lib/dashboard-paths.js +8 -0
  66. package/dist/lib/env.d.ts +9 -0
  67. package/dist/lib/env.js +55 -0
  68. package/dist/lib/errors.d.ts +22 -0
  69. package/dist/lib/errors.js +90 -0
  70. package/dist/lib/hosted.d.ts +2 -0
  71. package/dist/lib/hosted.js +7 -0
  72. package/dist/lib/http.d.ts +59 -0
  73. package/dist/lib/http.js +172 -0
  74. package/dist/lib/jwt.d.ts +1 -0
  75. package/dist/lib/jwt.js +31 -0
  76. package/dist/lib/locale.d.ts +12 -0
  77. package/dist/lib/locale.js +51 -0
  78. package/dist/lib/pkce.d.ts +20 -0
  79. package/dist/lib/pkce.js +124 -0
  80. package/dist/lib/storage-adapter.d.ts +15 -0
  81. package/dist/lib/storage-adapter.js +91 -0
  82. package/dist/lib/types.d.ts +339 -0
  83. package/dist/lib/types.js +1 -0
  84. package/dist/newsletter/client.d.ts +140 -0
  85. package/dist/newsletter/client.js +85 -0
  86. package/dist/payments/client.d.ts +352 -0
  87. package/dist/payments/client.js +323 -0
  88. package/dist/push/client.d.ts +110 -0
  89. package/dist/push/client.js +179 -0
  90. package/dist/realtime/client.d.ts +131 -0
  91. package/dist/realtime/client.js +513 -0
  92. package/dist/server/analytics.d.ts +176 -0
  93. package/dist/server/analytics.js +49 -0
  94. package/dist/server/cache.d.ts +74 -0
  95. package/dist/server/cache.js +154 -0
  96. package/dist/server/emails.d.ts +142 -0
  97. package/dist/server/emails.js +123 -0
  98. package/dist/server/events.d.ts +357 -0
  99. package/dist/server/events.js +219 -0
  100. package/dist/server/functions.d.ts +40 -0
  101. package/dist/server/functions.js +1 -0
  102. package/dist/server/http-utils.d.ts +10 -0
  103. package/dist/server/http-utils.js +115 -0
  104. package/dist/server/index.d.ts +195 -0
  105. package/dist/server/index.js +314 -0
  106. package/dist/server/payments.d.ts +218 -0
  107. package/dist/server/payments.js +150 -0
  108. package/dist/server/push.d.ts +85 -0
  109. package/dist/server/push.js +37 -0
  110. package/dist/server/usage.d.ts +43 -0
  111. package/dist/server/usage.js +8 -0
  112. package/dist/storage/client.d.ts +143 -0
  113. package/dist/storage/client.js +224 -0
  114. package/package.json +52 -4
  115. package/skill/usebecky/SKILL.md +339 -0
  116. package/skill/usebecky/references/access-rules.md +307 -0
  117. package/skill/usebecky/references/addons.md +68 -0
  118. package/skill/usebecky/references/analytics.md +166 -0
  119. package/skill/usebecky/references/android.md +434 -0
  120. package/skill/usebecky/references/auth.md +379 -0
  121. package/skill/usebecky/references/cache.md +51 -0
  122. package/skill/usebecky/references/components.md +127 -0
  123. package/skill/usebecky/references/emails.md +105 -0
  124. package/skill/usebecky/references/expo.md +147 -0
  125. package/skill/usebecky/references/functions.md +99 -0
  126. package/skill/usebecky/references/hosting.md +119 -0
  127. package/skill/usebecky/references/http-api.md +233 -0
  128. package/skill/usebecky/references/ios.md +355 -0
  129. package/skill/usebecky/references/payments.md +493 -0
  130. package/skill/usebecky/references/realtime.md +143 -0
  131. package/skill/usebecky/references/scheduled-jobs.md +82 -0
  132. package/skill/usebecky/references/sdk.md +838 -0
  133. package/skill/usebecky/references/storage.md +210 -0
  134. package/skill/usebecky/references/templates.md +191 -0
  135. package/skill/usebecky/references/wordpress.md +87 -0
package/README.md CHANGED
@@ -1,3 +1,702 @@
1
- # Temporary Holding Version
1
+ # usebecky
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **One package for your whole backend:** sign-in (email, magic links, Google/GitHub/Apple), a Postgres database with an instant API, file storage, realtime updates, and Stripe payments.
4
+
5
+ ```sh
6
+ npm install usebecky
7
+ ```
8
+
9
+ usebecky is a hosted service: create a project at https://app.usebecky.com, then run `npx usebecky init` in your app to connect it.
10
+
11
+ - **Never throws.** Every call returns `{ data, error }`. Check `error`, then use `data`.
12
+ - **Plain-English errors.** Every error has a `message` that says what went wrong and usually a `hint` that says what to do.
13
+ - **Autocomplete everywhere.** Run `npx usebecky types` and your table names, columns and function arguments autocomplete.
14
+ - **Zero dependencies.** Works in browsers, Node 22.18+, Next.js, Vite, Expo / React Native, Deno and Bun.
15
+
16
+ ---
17
+
18
+ ## Contents
19
+
20
+ 1. [Quickstart (5 minutes)](#quickstart-5-minutes)
21
+ 2. [The one rule: `{ data, error }`](#the-one-rule--data-error-)
22
+ 3. [Framework recipes](#framework-recipes): Next.js, React + Vite, Express, Expo
23
+ 4. [Reference](#reference): auth, database, storage, realtime, payments, server, events, functions, CLI
24
+ 5. [TypeScript](#typescript)
25
+ 6. [Errors you might see](#errors-you-might-see)
26
+ 7. [Keys and security](#keys-and-security)
27
+
28
+ ---
29
+
30
+ ## Quickstart (5 minutes)
31
+
32
+ ### 1. Connect your app
33
+
34
+ In your app's folder:
35
+
36
+ ```sh
37
+ npx usebecky init
38
+ ```
39
+
40
+ This signs you in, lets you pick (or create) a project, detects your framework, writes your keys to `.env.local` or `.env`, makes sure those files are git-ignored, and creates the client file `src/lib/usebecky.ts` (`lib/usebecky.ts` in apps without a `src` folder). For a Vite app it looks like this (Next.js and Expo get their own env variable names, see [Framework recipes](#framework-recipes)):
41
+
42
+ ```ts
43
+ // src/lib/usebecky.ts
44
+ import { createClient } from 'usebecky'
45
+
46
+ export const baas = createClient(
47
+ import.meta.env.VITE_USEBECKY_URL,
48
+ import.meta.env.VITE_USEBECKY_PUBLISHABLE_KEY,
49
+ )
50
+ ```
51
+
52
+ > Prefer to do it by hand? Copy the **publishable key** from **Dashboard → Settings → API keys** and pass it in: `createClient('ub_pk_…')`. The client talks to the hosted usebecky API (`https://api.usebecky.com`, exported as `HOSTED_API_URL`), so the key is all it needs.
53
+
54
+ The examples below import this client with `import { baas } from './lib/usebecky'` (a file directly inside `src/`, like `src/main.ts`). Examples that start with `// inside an async function:` are pieces to put in your own `async` function or click handler.
55
+
56
+ ### 2. Sign in with Google
57
+
58
+ ```ts
59
+ // src/main.ts
60
+ import { baas } from './lib/usebecky'
61
+
62
+ // A click on <button id="google"> sends the user to Google and back to this page, signed in.
63
+ document.querySelector('#google')?.addEventListener('click', () => baas.auth.signInWith('google'))
64
+
65
+ // React to sign-in and sign-out anywhere in your app:
66
+ baas.auth.onAuthStateChange((event, session) => {
67
+ console.log(event, session?.user.email) // 'INITIAL_SESSION' | 'SIGNED_IN' | 'SIGNED_OUT' | ...
68
+ })
69
+ ```
70
+
71
+ Email + password, magic links and Google sign-in work right away: a new project starts with Google on, through the Google app usebecky manages, so there are no keys to paste. GitHub is one click in Dashboard → Auth → Sign-in methods; Apple needs your own keys there.
72
+
73
+ ```ts
74
+ // inside an async function:
75
+ const email = 'ada@example.com'
76
+ const password = 'correct-horse-battery-staple'
77
+
78
+ await baas.auth.signUp({ email, password })
79
+ await baas.auth.signIn({ email, password })
80
+ await baas.auth.sendMagicLink(email, { createUser: true }) // email with a link + 6-digit code
81
+ await baas.auth.verifyCode(email, '123456') // sign in with the code
82
+ await baas.auth.signOut()
83
+ ```
84
+
85
+ The session is saved (localStorage in browsers) and refreshed automatically before it expires.
86
+
87
+ ### 3. Read and write data
88
+
89
+ Create a table in **Dashboard → Database** (pick the **"Only the user who created a row can see it"** preset), or run this in the SQL editor:
90
+
91
+ ```sql
92
+ create table todos (
93
+ id uuid primary key default gen_random_uuid(),
94
+ user_id uuid not null default auth.uid() references auth.users on delete cascade,
95
+ title text not null,
96
+ done boolean not null default false,
97
+ created_at timestamptz default now()
98
+ );
99
+ alter table todos enable row level security;
100
+ create policy "owner" on todos using (user_id = auth.uid()) with check (user_id = auth.uid());
101
+ ```
102
+
103
+ Then:
104
+
105
+ ```ts
106
+ // inside an async function:
107
+ // Add a todo (and get it back)
108
+ const { data: todo, error } = await baas.from('todos').insert({ title: 'Buy milk' }).select().single()
109
+ if (error) return console.log(error.message)
110
+
111
+ // List my open todos, newest first
112
+ const { data: todos } = await baas
113
+ .from('todos')
114
+ .select('id, title, done')
115
+ .eq('done', false)
116
+ .order('created_at', { ascending: false })
117
+
118
+ // Tick one off, delete another
119
+ await baas.from('todos').update({ done: true }).eq('id', todo.id)
120
+ await baas.from('todos').delete().eq('id', todo.id)
121
+ ```
122
+
123
+ The policy means each user only ever sees their own rows. No backend code needed.
124
+
125
+ ### 4. Live updates
126
+
127
+ Turn on realtime for the table (**Dashboard → Realtime**), then:
128
+
129
+ ```ts
130
+ // inside an async function:
131
+ const stop = baas.realtime.subscribe('todos', (change) => {
132
+ console.log(change.event, change.new) // 'INSERT' | 'UPDATE' | 'DELETE'
133
+ })
134
+
135
+ stop() // when you're done
136
+ ```
137
+
138
+ You only receive rows you're allowed to see.
139
+
140
+ ### 5. Take payments
141
+
142
+ Connect Stripe and create a product with monthly/yearly prices in **Dashboard → Payments**. Then:
143
+
144
+ ```ts
145
+ // inside an async function:
146
+ await baas.payments.checkout('pro_monthly', { successUrl: location.origin + '/thanks' }) // sends the user to Stripe Checkout
147
+ await baas.payments.portal() // change plan, cancel, update card
148
+
149
+ const { data: isPro } = await baas.payments.hasAccess('pro')
150
+ if (isPro) document.querySelector('#pro-features')?.removeAttribute('hidden')
151
+ ```
152
+
153
+ You can also protect data with a policy: `using (billing.has_access('pro'))`.
154
+
155
+ ### 6. Use it on your server
156
+
157
+ ```ts
158
+ // inside an Express route handler:
159
+ import { baas } from 'usebecky/server' // server only: reads USEBECKY_SECRET_KEY
160
+
161
+ const user = await baas.auth.getUser(req) // who is calling? (User or null)
162
+ const { data } = await baas.as(req).from('todos').select() // as that user: same rules as the browser
163
+ if (await baas.payments.hasAccess(user, 'pro')) res.json({ todos: data, pro: true })
164
+ ```
165
+
166
+ ---
167
+
168
+ ## The one rule: `{ data, error }`
169
+
170
+ Every call resolves to `{ data, error }` and **never throws** for API errors (even when you're offline). So you never need `try/catch`:
171
+
172
+ ```ts
173
+ // inside an async function:
174
+ const { data, error } = await baas.from('todos').select()
175
+ if (error) {
176
+ console.log(error.message) // "The table "todo" does not exist in your database."
177
+ console.log(error.hint) // "Did you mean "todos"? Table names are case-sensitive."
178
+ console.log(error.code) // "table_not_found" (stable, use it in your code)
179
+ console.log(error.status) // 404 (0 = the request never reached the server)
180
+ return
181
+ }
182
+ console.log(data) // TypeScript knows data is not null here
183
+ ```
184
+
185
+ Database calls also return `count` (when you ask for it) and `status`.
186
+
187
+ ---
188
+
189
+ ## Framework recipes
190
+
191
+ ### Next.js (App Router)
192
+
193
+ `npx usebecky init` writes `.env.local`:
194
+
195
+ ```sh
196
+ NEXT_PUBLIC_USEBECKY_URL=https://…
197
+ NEXT_PUBLIC_USEBECKY_PUBLISHABLE_KEY=ub_pk_…
198
+ USEBECKY_URL=https://…
199
+ USEBECKY_SECRET_KEY=ub_sk_… # server only, never prefix with NEXT_PUBLIC_
200
+ ```
201
+
202
+ **Browser** (client components):
203
+
204
+ ```ts
205
+ // lib/usebecky.ts
206
+ import { createClient } from 'usebecky'
207
+ export const baas = createClient(process.env.NEXT_PUBLIC_USEBECKY_URL!, process.env.NEXT_PUBLIC_USEBECKY_PUBLISHABLE_KEY!)
208
+ ```
209
+
210
+ ```tsx
211
+ // app/login/page.tsx
212
+ 'use client'
213
+ import { baas } from '@/lib/usebecky'
214
+
215
+ export default function Login() {
216
+ return <button onClick={() => baas.auth.signInWith('google', { redirectTo: `${location.origin}/dashboard` })}>Continue with Google</button>
217
+ }
218
+ ```
219
+
220
+ **Server components, route handlers and server actions.** The browser client mirrors the access token into a `ub-access-token` cookie, so the server can tell who's signed in:
221
+
222
+ ```tsx
223
+ // app/dashboard/page.tsx (server component)
224
+ import { cookies } from 'next/headers'
225
+ import { redirect } from 'next/navigation'
226
+ import { baas } from 'usebecky/server'
227
+
228
+ export default async function Dashboard() {
229
+ const jar = await cookies() // cookies() is async in Next.js 15+
230
+ const user = await baas.auth.getUser(jar)
231
+ if (!user) redirect('/login')
232
+ const { data: todos } = await baas.as(jar).from('todos').select()
233
+ return <pre>{JSON.stringify({ email: user.email, todos }, null, 2)}</pre>
234
+ }
235
+ ```
236
+
237
+ ```ts
238
+ // app/api/me/route.ts
239
+ import { baas } from 'usebecky/server'
240
+
241
+ export async function GET(request: Request) {
242
+ const user = await baas.auth.getUser(request) // Authorization header or the cookie
243
+ if (!user) return Response.json({ error: 'Sign in first' }, { status: 401 })
244
+ return Response.json({ user })
245
+ }
246
+ ```
247
+
248
+ ```ts
249
+ // app/api/usebecky-events/route.ts (webhooks from usebecky)
250
+ import { baas } from 'usebecky/server'
251
+
252
+ baas.events.on('subscription.created', async (event) => {
253
+ console.log('New subscriber!', event.data)
254
+ })
255
+
256
+ export const POST = baas.events.fetchHandler()
257
+ ```
258
+
259
+ ### React + Vite
260
+
261
+ Vite only exposes env vars that start with `VITE_`, and you read them with `import.meta.env`:
262
+
263
+ ```sh
264
+ # .env.local
265
+ VITE_USEBECKY_URL=https://…
266
+ VITE_USEBECKY_PUBLISHABLE_KEY=ub_pk_…
267
+ ```
268
+
269
+ ```ts
270
+ // src/lib/usebecky.ts
271
+ import { createClient } from 'usebecky'
272
+ export const baas = createClient(import.meta.env.VITE_USEBECKY_URL, import.meta.env.VITE_USEBECKY_PUBLISHABLE_KEY)
273
+ ```
274
+
275
+ ```ts
276
+ // src/useUser.ts
277
+ import { useEffect, useState } from 'react'
278
+ import type { User } from 'usebecky'
279
+ import { baas } from './lib/usebecky'
280
+
281
+ export function useUser() {
282
+ const [user, setUser] = useState<User | null>(baas.auth.getSession().data.session?.user ?? null)
283
+ useEffect(() => baas.auth.onAuthStateChange((_event, session) => setUser(session?.user ?? null)), [])
284
+ return user
285
+ }
286
+ ```
287
+
288
+ ```tsx
289
+ // src/Todos.tsx
290
+ import { useEffect, useState } from 'react'
291
+ import { baas } from './lib/usebecky'
292
+
293
+ export function Todos() {
294
+ const [todos, setTodos] = useState<any[]>([])
295
+ useEffect(() => {
296
+ const load = () => baas.from('todos').select().order('created_at').then(({ data }) => setTodos(data ?? []))
297
+ load()
298
+ return baas.realtime.subscribe('todos', load) // returns the unsubscribe function
299
+ }, [])
300
+ return <ul>{todos.map((t) => <li key={t.id}>{t.title}</li>)}</ul>
301
+ }
302
+ ```
303
+
304
+ ### Express
305
+
306
+ ```sh
307
+ # .env
308
+ USEBECKY_URL=https://…
309
+ USEBECKY_PUBLISHABLE_KEY=ub_pk_…
310
+ USEBECKY_SECRET_KEY=ub_sk_…
311
+ USEBECKY_WEBHOOK_SECRET=whsec_… # Dashboard → Settings → Webhooks
312
+ ```
313
+
314
+ ```js
315
+ // server.js. Run with: node --env-file=.env server.js
316
+ import express from 'express'
317
+ import { baas } from 'usebecky/server'
318
+
319
+ const app = express()
320
+
321
+ // Webhooks first: the handler reads the raw body itself.
322
+ baas.events.on('subscription.canceled', async (event) => { /* email the user, etc. */ })
323
+ app.post('/api/usebecky-events', baas.events.handler())
324
+
325
+ app.use(express.json())
326
+ app.use(baas.auth.middleware()) // req.user = the signed-in user, or null
327
+
328
+ app.get('/api/todos', baas.auth.requireUser(), async (req, res) => {
329
+ const { data, error } = await baas.as(req).from('todos').select() // RLS applies
330
+ if (error) return res.status(error.status || 500).json({ error })
331
+ res.json(data)
332
+ })
333
+
334
+ app.get('/api/premium', baas.auth.requireUser(), async (req, res) => {
335
+ if (!(await baas.payments.hasAccess(req.user, 'pro'))) return res.status(402).json({ error: 'Upgrade to Pro' })
336
+ res.json({ secret: 'the good stuff' })
337
+ })
338
+
339
+ app.listen(3000)
340
+ ```
341
+
342
+ From your frontend, call these routes with the user's token:
343
+
344
+ ```ts
345
+ // inside an async function:
346
+ const token = baas.auth.getSession().data.session?.access_token
347
+ await fetch('/api/todos', { headers: { Authorization: `Bearer ${token}` } })
348
+ ```
349
+
350
+ (Same-site requests also carry the `ub-access-token` cookie, so plain links and forms work too.)
351
+
352
+ ### Expo / React Native
353
+
354
+ ```sh
355
+ npx expo install usebecky @react-native-async-storage/async-storage expo-linking expo-web-browser
356
+ ```
357
+
358
+ (Until usebecky is on npm, install it from the file you packed, see the note at the top, and leave `usebecky` out of this command.)
359
+
360
+ ```sh
361
+ # .env
362
+ EXPO_PUBLIC_USEBECKY_URL=https://…
363
+ EXPO_PUBLIC_USEBECKY_PUBLISHABLE_KEY=ub_pk_…
364
+ ```
365
+
366
+ ```ts
367
+ // lib/usebecky.ts
368
+ import AsyncStorage from '@react-native-async-storage/async-storage'
369
+ import { createClient } from 'usebecky'
370
+
371
+ export const baas = createClient(process.env.EXPO_PUBLIC_USEBECKY_URL!, process.env.EXPO_PUBLIC_USEBECKY_PUBLISHABLE_KEY!, {
372
+ storage: AsyncStorage, // keeps users signed in after the app restarts
373
+ detectSessionInUrl: false, // there is no browser URL in a native app
374
+ })
375
+ ```
376
+
377
+ Social sign-in with a deep link. Set `"scheme": "com.example.mynotes"` in `app.json` (use your app's bundle ID / application ID: it is unique to your app, so another app can't register the same scheme and catch the sign-in), and add `com.example.mynotes://**` (plus `exp://**` while you use Expo Go) to **Dashboard → Settings → General → Your app’s addresses**:
378
+
379
+ ```ts
380
+ // inside an async function:
381
+ import * as Linking from 'expo-linking'
382
+ import * as WebBrowser from 'expo-web-browser'
383
+
384
+ const redirectTo = Linking.createURL('auth') // com.example.mynotes://auth in a build, exp://…/--/auth in Expo Go
385
+ const { data, error } = await baas.auth.signInWith('google', { redirectTo, skipBrowserRedirect: true })
386
+ if (error) return console.log(error.message)
387
+ const res = await WebBrowser.openAuthSessionAsync(data.url, redirectTo)
388
+ if (res.type === 'success') await baas.auth.setSessionFromUrl(res.url)
389
+ ```
390
+
391
+ `signInWith` uses PKCE: it keeps a one-time secret in `storage` (AsyncStorage) and `setSessionFromUrl` swaps the `?code=` in the redirect for a session, so tokens never appear in the redirect address.
392
+
393
+ Checkout works the same way, and app links are fine as return addresses when they are allowed (the server sends Stripe a web address that bounces back to your app):
394
+
395
+ ```ts
396
+ // inside an async function:
397
+ import * as Linking from 'expo-linking'
398
+ import * as WebBrowser from 'expo-web-browser'
399
+
400
+ const returnTo = Linking.createURL('checkout')
401
+ const { data } = await baas.payments.checkout('pro_monthly', { successUrl: returnTo, cancelUrl: returnTo })
402
+ if (data) await WebBrowser.openAuthSessionAsync(data.url, returnTo) // no automatic redirect outside a browser
403
+ ```
404
+
405
+ Full walkthrough: https://usebecky.com/docs/frameworks/expo
406
+
407
+ ---
408
+
409
+ ## Reference
410
+
411
+ ### `createClient(publishableKey, options?)` / `createClient(url?, publishableKey?, options?)`
412
+
413
+ The publishable key is all it needs: the URL defaults to the hosted API (`HOSTED_API_URL`). With no arguments it reads `USEBECKY_PUBLISHABLE_KEY` (or the `NEXT_PUBLIC_` / `EXPO_PUBLIC_` versions). A URL passed in, or set as `USEBECKY_URL` (and its prefixed versions), takes precedence over the hosted default.
414
+
415
+ | Option | Default | What it does |
416
+ |---|---|---|
417
+ | `storage` | localStorage, else memory | Where the session is kept. Anything with `getItem/setItem/removeItem` (sync or async). |
418
+ | `autoRefresh` | `true` | Refresh the access token before it expires (one refresh at a time, even across tabs). |
419
+ | `detectSessionInUrl` | `true` | Finish OAuth / magic-link / password-reset redirects (reads `?code=…` or `#access_token=…`, then cleans the URL). |
420
+ | `cookie` | `true` in browsers | Mirror the access token to a `ub-access-token` cookie so your server can read it. |
421
+ | `fetch` | global `fetch` | Custom fetch. |
422
+ | `headers` | | Extra headers on every request. |
423
+ | `realtime` | | `{ WebSocket }` for runtimes without a global WebSocket. |
424
+ | `locale` | the browser's language | Language of the emails your users get, like `'de'` (sent as `Accept-Language`). Change it later with `baas.setLocale('de')`. |
425
+
426
+ ### Auth: `baas.auth`
427
+
428
+ | Call | Returns |
429
+ |---|---|
430
+ | `signUp({ email, password, data?, redirectTo?, locale? })` | `{ user, session }` (`session` is `null` when email confirmation is on). `locale`: the email's language, on every call that sends one |
431
+ | `signIn({ email, password })` | `{ user, session, mfaRequired? }`. If `mfaRequired`, ask for the 6-digit code and call `mfa.verify()` |
432
+ | `signInWith('google' \| 'github' \| 'apple', { redirectTo?, skipBrowserRedirect? })` | redirects; `{ provider, url }`. Uses PKCE: the redirect carries a one-time `?code=`, never tokens |
433
+ | `sendMagicLink(email, { redirectTo?, createUser? })` | `{}`. Existing users only, unless `createUser: true` |
434
+ | `verifyCode(email, code, type = 'magiclink')` | `{ user, session }` |
435
+ | `resetPassword(email, { redirectTo? })` | `{}`; after the redirect you get `PASSWORD_RECOVERY`, then call `updateUser({ password })` |
436
+ | `updateUser({ email?, password?, data? })` | `{ user }` |
437
+ | `signOut({ everywhere? })` | `{ error }` |
438
+ | `getUser()` | `{ user }` fresh from the server (`null` when signed out) |
439
+ | `getSession()` | `{ session }` from memory, synchronous |
440
+ | `onAuthStateChange((event, session) => {})` | an unsubscribe function. Events: `INITIAL_SESSION`, `SIGNED_IN`, `SIGNED_OUT`, `TOKEN_REFRESHED`, `USER_UPDATED`, `PASSWORD_RECOVERY`, `MFA_CHALLENGE_VERIFIED` |
441
+ | `refreshSession()` | `{ session }` |
442
+ | `setSessionFromUrl(url)` | finish a redirect yourself (mobile deep links): swaps `?code=` for a session (or reads `#access_token=`) |
443
+ | `exchangeCodeForSession(authCode)` | `{ session }` for a `?code=` you read yourself |
444
+ | `settings()` | which sign-in methods are enabled |
445
+ | `mfa.enroll()` / `mfa.verify(factorId, code)` / `mfa.unenroll(factorId)` | authenticator apps (TOTP). `enroll()` gives `{ id, secret, uri }`; show `uri` as a QR code |
446
+
447
+ ### Database: `baas.from(table)` and `baas.rpc(fn, args)`
448
+
449
+ ```ts
450
+ // inside an async function:
451
+ const id = '5f2b8c1e-7d4a-4e9b-a3c6-0f1e2d3c4b5a'
452
+
453
+ await baas.from('todos').select('id, title, author:profiles(name)', { count: 'exact' })
454
+ await baas.from('todos').insert([{ title: 'Buy milk' }, { title: 'Walk the dog' }]) // one row or an array; add .select() to get the rows back
455
+ await baas.from('todos').update({ done: true }).eq('id', id)
456
+ await baas.from('todos').upsert([{ id, title: 'Buy oat milk' }], { onConflict: 'id' })
457
+ await baas.from('todos').delete().eq('id', id)
458
+ await baas.rpc('my_function', { arg: 1 })
459
+ ```
460
+
461
+ **Filters:** `eq` `neq` `gt` `gte` `lt` `lte` `like` `ilike` (`%` wildcard) `is` (null/true/false) `in` `contains` `containedBy` `overlaps` `textSearch` `not(col, op, value)` `or('a.eq.1,b.eq.2')` `match({ a: 1 })` `filter(col, op, value)`
462
+
463
+ **Modifiers:** `select(cols)` `order(col, { ascending })` `limit(n)` `range(from, to)` `single()` `maybeSingle()` `abortSignal(signal)`
464
+
465
+ - `select('*, comments(*)')` embeds related tables through foreign keys. Rename with `author:profiles(name)`.
466
+ - `{ count: 'exact' }` adds the total to `count`; add `head: true` to skip the rows.
467
+ - `single()` returns one object (an error if there isn't exactly one); `maybeSingle()` returns `null` when nothing matches.
468
+
469
+ ### Storage: `baas.storage.from(bucket)`
470
+
471
+ ```ts
472
+ // inside an async function:
473
+ const user = baas.auth.getSession().data.session?.user
474
+ const file = document.querySelector<HTMLInputElement>('input[type=file]')?.files?.[0]
475
+ if (!user || !file) return
476
+
477
+ const avatars = baas.storage.from('avatars')
478
+ await avatars.upload(`${user.id}/me.png`, file, { upsert: true })
479
+ await avatars.download(`${user.id}/me.png`) // { data: Blob }
480
+ avatars.getPublicUrl(`${user.id}/me.png`) // { data: { publicUrl } } for public buckets
481
+ await avatars.createSignedUrl(`${user.id}/me.png`, 60) // { data: { signedUrl } } link valid 60s
482
+ await avatars.list(`${user.id}/`, { limit: 20 })
483
+ await avatars.remove([`${user.id}/old.png`])
484
+ await avatars.move('a.png', 'b.png'); await avatars.copy('a.png', 'c.png')
485
+ ```
486
+
487
+ Uploads are allowed by policies on `storage.objects` (pick a preset in **Dashboard → Storage**, e.g. "users can manage their own folder").
488
+
489
+ ### Realtime: `baas.realtime`
490
+
491
+ ```ts
492
+ // inside an async function:
493
+ // Table changes
494
+ const stop = baas.realtime.subscribe('messages', { event: 'INSERT', filter: 'room_id=eq.42' }, (change) => {
495
+ console.log(change.event, change.new, change.old, change.table, change.commit_timestamp)
496
+ })
497
+
498
+ // Broadcast + presence ("who's online", typing indicators, cursors)
499
+ const room = baas.realtime.channel('room:42')
500
+ room.on('typing', (payload) => console.log(payload))
501
+ room.send('typing', { user: 'Ada' })
502
+ room.track({ name: 'Ada' })
503
+ room.onPresence((state) => console.log(Object.values(state))) // room.presenceKey is your own key
504
+ room.leave()
505
+ stop()
506
+ ```
507
+
508
+ One connection is shared by everything, opened on first use, and reconnected (and re-subscribed) automatically.
509
+
510
+ ### Payments: `baas.payments`
511
+
512
+ | Call | Returns |
513
+ |---|---|
514
+ | `products()` | your catalog with prices (amounts in cents); `has_download` tells you if it unlocks a file |
515
+ | `checkout(priceKey, { successUrl?, cancelUrl?, redirect? })` | redirects to Stripe; `{ url, id }`. Error `already_subscribed` / `already_purchased` if they already own it |
516
+ | `portal({ returnUrl? })` | redirects to the Stripe customer portal; `{ url }`. Error `portal_not_configured` until you save the portal settings in Stripe |
517
+ | `me()` | `{ subscriptions, purchases, entitlements }` |
518
+ | `hasAccess(feature)` | `true`/`false` (`false` when signed out) |
519
+ | `download(productKey)` | `{ url, expiresIn }` signed link to a purchased file |
520
+
521
+ ### Server: `usebecky/server`
522
+
523
+ ```ts
524
+ import { baas, createServerClient } from 'usebecky/server'
525
+ // baas reads USEBECKY_SECRET_KEY on first use (and USEBECKY_URL if set; default: the hosted API).
526
+ // Or explicitly: createServerClient('ub_sk_…') or createServerClient({ secretKey, url?, publishableKey?, webhookSecret? })
527
+ ```
528
+
529
+ | Call | What it does |
530
+ |---|---|
531
+ | `auth.getUser(req \| request \| cookies() \| token)` | The signed-in `User` or `null`. Reads `Authorization: Bearer …` or the `ub-access-token` cookie, verifies it with usebecky, caches it ~30s. |
532
+ | `auth.middleware()` | Express/Connect: sets `req.user` (or `null`). Never blocks. |
533
+ | `auth.requireUser()` | Express/Connect: 401 JSON unless signed in. |
534
+ | `as(req \| req.user \| token)` | `from`, `rpc`, `storage` **as that user** (Row Level Security applies). Without a user it uses the publishable key if set, otherwise returns `not_signed_in`. It never silently becomes admin. |
535
+ | `admin` | `from`, `rpc`, `storage` as **admin** (bypasses Row Level Security, so be careful). |
536
+ | `auth.admin.listUsers / createUser / getUserById / updateUser / deleteUser / inviteUser / signOutUser` | User management. `updateUser(id, { ban: '24h' \| 'forever' \| 'none' })` |
537
+ | `payments.hasAccess(userOrId, feature)` | `true`/`false`; never throws |
538
+ | `emails.send({ to, subject, text })` / `emails.send({ to, template, data })` | Send an email in your branded layout, or one you made in Dashboard → Emails. Also `batch`, `get`, `cancel`, attachments, `sendAt`, `tags`, `idempotencyKey`, `locale` |
539
+ | `functions.invoke(name, { body, method })` | Run one of your Functions with the secret key ("servers only" functions work); `as(req).functions.invoke` calls it as that user |
540
+ | `cache.get / set / delete / getOrSet / limit` | The built-in cache (Business): `set('weather:berlin', data, { ttl: '10m' })`, `get(key)` → value or `null`, `limit('signup:' + ip, 5, '1h')` → `{ allowed, remaining, resetAt, retryAfter }`. Fails open (never throws on outages) |
541
+ | `events` | Signed webhooks, see below |
542
+
543
+ ### Events (webhooks): `baas.events`
544
+
545
+ usebecky POSTs signed events to your server (`user.created`, `subscription.created`, `subscription.canceled`, `purchase.completed`, `payment.failed`, …). Add your endpoint in **Dashboard → Settings → Webhooks** and copy its signing secret into `USEBECKY_WEBHOOK_SECRET`.
546
+
547
+ ```js
548
+ // server.js: server only (it uses your secret key and USEBECKY_WEBHOOK_SECRET). Run with: node --env-file=.env server.js
549
+ import express from 'express'
550
+ import { baas } from 'usebecky/server'
551
+
552
+ baas.events.on('subscription.created', async (event) => console.log(event.id, event.type, event.data))
553
+ baas.events.on('subscription.*', async (event) => console.log('subscription event', event.type)) // a whole group
554
+ baas.events.on('*', async (event) => console.log('event', event.type)) // everything
555
+
556
+ const app = express()
557
+ app.post('/api/usebecky-events', baas.events.handler()) // Express / node:http; mount it before express.json()
558
+
559
+ // Or do it yourself: the raw body plus the usebecky-signature header (verify throws if invalid)
560
+ app.post('/api/my-events', express.raw({ type: 'application/json' }), (req, res) => {
561
+ try {
562
+ const event = baas.events.verify(req.body, req.get('usebecky-signature'))
563
+ res.json({ received: event.id })
564
+ } catch {
565
+ res.status(400).json({ error: 'invalid signature' })
566
+ }
567
+ })
568
+
569
+ app.listen(3000)
570
+ ```
571
+
572
+ ```ts
573
+ // app/api/usebecky-events/route.ts: Next.js, Remix, Hono, Bun, Deno (any Fetch API handler)
574
+ import { baas } from 'usebecky/server'
575
+
576
+ baas.events.on('subscription.created', async (event) => console.log(event.data))
577
+
578
+ export const POST = baas.events.fetchHandler()
579
+ ```
580
+
581
+ Signatures are checked with a constant-time comparison, and events older than 5 minutes are rejected. If your handler throws, the response is a 500 and usebecky retries (10s, 1m, 5m, 30m, 2h). The same event can arrive twice, so use `event.id` to skip duplicates.
582
+
583
+ ### Functions: `baas.functions`
584
+
585
+ Your own code running on usebecky (Dashboard → Functions, or files in `usebecky/functions/` deployed with the CLI). From the browser client the call carries the signed-in user's token:
586
+
587
+ ```ts
588
+ // inside an async function:
589
+ const { data, error } = await baas.functions.invoke('send-welcome', { body: { plan: 'pro' } })
590
+ // options: method (default 'POST'), headers, query, path, responseType ('text' | 'blob'), signal
591
+ if (error) console.error(error.code, error.message) // function_error, function_timeout, not_signed_in, ...
592
+ else console.log(data) // parsed JSON, or text
593
+ ```
594
+
595
+ Write one with the types from `usebecky/server`:
596
+
597
+ ```ts
598
+ // usebecky/functions/send-welcome.ts
599
+ import type { FunctionHandler } from 'usebecky/server'
600
+
601
+ const handler: FunctionHandler = async (req, ctx) => {
602
+ const { plan } = (await req.json()) as { plan: string }
603
+ if (!ctx.user?.email) return new Response('Sign in first', { status: 401 })
604
+ await ctx.baas.emails.send({ to: ctx.user.email, subject: 'Welcome!', text: `You are on ${plan}.` })
605
+ return { sent: true }
606
+ }
607
+
608
+ export default handler
609
+ ```
610
+
611
+ ### CLI: `npx usebecky`
612
+
613
+ | Command | What it does |
614
+ |---|---|
615
+ | `init` | Pick or create a project, detect your framework, write `.env.local`/`.env`, git-ignore it, create the client file (`src/lib/usebecky.ts`, or `lib/usebecky.ts` without a `src` folder), print next steps |
616
+ | `login` / `logout` | Sign in to your usebecky account (token stored in `~/.usebecky/config.json`) |
617
+ | `projects` | List your projects |
618
+ | `types` | Generate `usebecky.types.ts` from your database |
619
+ | `open` | Open the dashboard for the linked project |
620
+ | `status` | Show the linked project and check that the API and your key work |
621
+ | `ai` (alias `skill`) | Teach your AI coding assistant to use usebecky: installs the skill into `.claude/skills/usebecky/` (Claude Code loads it automatically) and adds a usebecky section to `AGENTS.md` (Cursor, Codex, Copilot, Windsurf). Safe to re-run; `--force` replaces skill files you edited |
622
+ | `functions` | `new <name> [--template <id>]`, `deploy [name...]` (bundles with your project's esbuild: `npm install --save-dev esbuild`), `list`, `logs [name] [--errors]`, `secrets set NAME=value ...`, `secrets list`, `secrets unset NAME` |
623
+ | `deploy [dir]` | Put your website or Node.js app online with usebecky Hosting (Business plan): detects the framework, runs its build, uploads only changed files (a Node.js server goes up as one bundle with production packages), prints the preview and production addresses. `--site <name>`, `--prod` (put it live), `--no-build`. In CI: `USEBECKY_DEPLOY_TOKEN` + `--project` + `--site` |
624
+ | `hosting` | Your sites: `list`, `deploys`, `rollback [deploy]`, `promote <deploy>`, `env list\|set NAME=value\|unset NAME`, `domains list\|add\|check\|remove <domain>`, `logs [--follow]`, `github` (writes a GitHub Actions workflow that deploys on every push) |
625
+ | `analytics` | Add visitor analytics to a website: finds your publishable key and API URL (env file, `--key` / `--api-url`, or asks), detects the framework (plain HTML, Vite, CRA, Angular, Next.js, Astro, SvelteKit, Nuxt, Remix, React Router) and inserts the script tag once. Prints what changed; `--dry-run` previews. Never touches the secret key |
626
+
627
+ Flags: `--api-url <url>` (or `USEBECKY_API_URL`), `--project <ref>`, `--out <file>` (types), `--yes` (no questions; never overwrites), `--force` (`ai` only), `--key` and `--dry-run` (`analytics` only). `init` never overwrites an existing value in your env file without asking.
628
+
629
+ ---
630
+
631
+ ## TypeScript
632
+
633
+ Generate types from your database:
634
+
635
+ ```sh
636
+ npx usebecky types
637
+ ```
638
+
639
+ It writes `usebecky.types.ts` next to your `package.json`. Pass its `Database` type to `createClient`:
640
+
641
+ ```ts
642
+ // src/lib/usebecky.ts
643
+ import { createClient } from 'usebecky'
644
+ import type { Database } from '../../usebecky.types'
645
+
646
+ export const baas = createClient<Database>(
647
+ import.meta.env.VITE_USEBECKY_URL,
648
+ import.meta.env.VITE_USEBECKY_PUBLISHABLE_KEY,
649
+ )
650
+ ```
651
+
652
+ ```ts
653
+ // inside an async function:
654
+ const { data } = await baas.from('todos').select('id, title')
655
+ // ^? { id: string; title: string }[] | null
656
+ // @ts-expect-error: typo caught, 'titel' does not exist on todos
657
+ await baas.from('todos').insert({ titel: 'x' })
658
+ ```
659
+
660
+ Without generated types everything still works; values are just typed as `any`. Re-run `npx usebecky types` after you change your tables.
661
+
662
+ ---
663
+
664
+ ## Errors you might see
665
+
666
+ | `error.code` | What it means | What to do |
667
+ |---|---|---|
668
+ | *(thrown)* `createClient() is missing your publishable key…` | No key was passed and the env vars aren't set. | Run `npx usebecky init`, or set the env vars from **Dashboard → Settings → API keys**. In Vite, pass `import.meta.env.VITE_…` values explicitly. Restart your dev server after editing env files. |
669
+ | *(thrown)* `usebecky/server: missing USEBECKY_SECRET_KEY` | The server client has no secret key. | Add it to your server's `.env`. Node doesn't read `.env` on its own: run `node --env-file=.env server.js`. |
670
+ | `network_error` (status 0) | The request never reached usebecky: offline, wrong URL, or a firewall. | Check your connection and that the URL is right. |
671
+ | `invalid_api_key` / `missing_api_key` | The key is wrong, was rolled, or is missing. | Copy it again from **Dashboard → Settings → API keys**. |
672
+ | `invalid_credentials` | Wrong email or password. | Check for typos or use `resetPassword()`. |
673
+ | `not_signed_in` | That call needs a signed-in user. | Sign in first. On your server, send the token (`Authorization: Bearer …`) or use `requireUser()`. |
674
+ | `permission_denied` (403) | A Row Level Security policy blocked it. | Add a policy for that action (Dashboard → Database → Access rules). The `hint` says which table. |
675
+ | Empty `data` but no error | RLS hides rows you're not allowed to see. | This is usually right! Check you're signed in and that a SELECT policy allows the rows. |
676
+ | `table_not_found` / `column_not_found` | A name doesn't exist (names are case-sensitive). | The `hint` suggests the closest match. Re-run `npx usebecky types` to catch these at compile time. |
677
+ | `not_single_row` (406) | `.single()` found 0 or several rows. | Add a filter like `.eq('id', id)`, or use `.maybeSingle()`. |
678
+ | `invalid_refresh_token` | The session expired or was signed out elsewhere. | The user is signed out (`SIGNED_OUT` fires); ask them to sign in again. |
679
+ | `secret_key_required` | You called an admin endpoint with the publishable key. | Do it from your server with `usebecky/server`. |
680
+ | `not_purchased` | `payments.download()` for something the user hasn't bought. | Send them to `checkout()`. |
681
+ | `already_subscribed` / `already_purchased` (409) | `checkout()` for something the user already has. | Show a "Manage billing" button (`portal()`) instead. |
682
+ | `portal_not_configured` (409) | Stripe's customer portal isn't set up yet. | Save the portal settings in your Stripe Dashboard (Settings → Billing → Customer portal). |
683
+ | `token_expired` | The access token expired. | Usually handled for you: the SDK refreshes the session and retries once. |
684
+ | `invalid_signature` / `stale_signature` | A webhook didn't verify. | Check `USEBECKY_WEBHOOK_SECRET`, pass the raw body (mount the handler before `express.json()`), and check your server's clock. |
685
+ | `rate_limited` (429) | You hit a rate limit. | Wait a moment and retry. |
686
+ | Realtime: `Realtime subscription to "x" failed…` (console) | Realtime isn't enabled for the table, or you can't read it. | Enable it in **Dashboard → Realtime**. Pass `onError` to handle it yourself. |
687
+
688
+ Every error has `code`, `message`, `status` and often `hint`. `console.log(error.message, error.hint)` usually tells you exactly what to fix.
689
+
690
+ ---
691
+
692
+ ## Keys and security
693
+
694
+ - **Publishable key (`ub_pk_…`)** is safe in browsers and apps. What it can do is limited by your Row Level Security policies.
695
+ - **Secret key (`ub_sk_…`)** bypasses all policies. Use it **only on your server**, never with a `NEXT_PUBLIC_`/`VITE_`/`EXPO_PUBLIC_` prefix. The SDK warns loudly if you pass it to `createClient()` in a browser. If it leaks, roll it in **Dashboard → Settings → API keys**.
696
+ - `baas.as(req)` runs as the user (policies apply). `baas.admin` runs as admin. Reach for `as` first.
697
+
698
+ ## Example app
699
+
700
+ [`examples/saas-starter`](../../examples/saas-starter) is a complete mini SaaS with sign-in (email, Google, magic link), todos with realtime, a pricing page with a monthly/yearly toggle and trial, Stripe checkout, a premium page, a paid download and webhook handling.
701
+
702
+ MIT License