create-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.
- package/README.md +80 -2
- package/dist/create.js +842 -0
- package/dist/extension-skill/usebecky-extension/SKILL.md +181 -0
- package/dist/extension-skill/usebecky-extension/references/accounts.md +125 -0
- package/dist/extension-skill/usebecky-extension/references/dev-server.md +102 -0
- package/dist/extension-skill/usebecky-extension/references/manifest.md +104 -0
- package/dist/extension-skill/usebecky-extension/references/oauth-and-tokens.md +179 -0
- package/dist/extension-skill/usebecky-extension/references/partner-api.md +87 -0
- package/dist/extension-skill/usebecky-extension/references/submit-and-pricing.md +31 -0
- package/dist/extension-skill/usebecky-extension/references/ui.md +172 -0
- package/dist/extension-skill/usebecky-extension/references/webhooks.md +97 -0
- package/dist/index.js +10 -0
- package/dist/keys.js +72 -0
- package/dist/platform.js +104 -0
- package/dist/pm.js +69 -0
- package/dist/prompts.js +242 -0
- package/dist/scaffold.js +108 -0
- package/dist/setup.js +130 -0
- package/dist/shared/ai.js +203 -0
- package/dist/shared/extension-skill.js +107 -0
- package/dist/shared/framework.js +460 -0
- package/dist/shared/hosted.js +8 -0
- package/dist/shared/ui.js +141 -0
- package/dist/skill/usebecky/SKILL.md +339 -0
- package/dist/skill/usebecky/references/access-rules.md +307 -0
- package/dist/skill/usebecky/references/addons.md +68 -0
- package/dist/skill/usebecky/references/analytics.md +166 -0
- package/dist/skill/usebecky/references/android.md +434 -0
- package/dist/skill/usebecky/references/auth.md +379 -0
- package/dist/skill/usebecky/references/cache.md +51 -0
- package/dist/skill/usebecky/references/components.md +127 -0
- package/dist/skill/usebecky/references/emails.md +105 -0
- package/dist/skill/usebecky/references/expo.md +147 -0
- package/dist/skill/usebecky/references/functions.md +99 -0
- package/dist/skill/usebecky/references/hosting.md +119 -0
- package/dist/skill/usebecky/references/http-api.md +233 -0
- package/dist/skill/usebecky/references/ios.md +355 -0
- package/dist/skill/usebecky/references/payments.md +493 -0
- package/dist/skill/usebecky/references/realtime.md +143 -0
- package/dist/skill/usebecky/references/scheduled-jobs.md +82 -0
- package/dist/skill/usebecky/references/sdk.md +838 -0
- package/dist/skill/usebecky/references/storage.md +210 -0
- package/dist/skill/usebecky/references/templates.md +191 -0
- package/dist/skill/usebecky/references/wordpress.md +87 -0
- package/dist/templates.js +74 -0
- package/package.json +37 -4
- package/templates/expo/App.tsx +48 -0
- package/templates/expo/README.md +59 -0
- package/templates/expo/_env.example +4 -0
- package/templates/expo/_gitignore +12 -0
- package/templates/expo/app.json +25 -0
- package/templates/expo/assets/icon.png +0 -0
- package/templates/expo/brand.ts +7 -0
- package/templates/expo/components/Avatar.tsx +75 -0
- package/templates/expo/components/ui.tsx +57 -0
- package/templates/expo/index.ts +4 -0
- package/templates/expo/lib/theme.ts +43 -0
- package/templates/expo/lib/usebecky.ts +15 -0
- package/templates/expo/package.json +29 -0
- package/templates/expo/screens/Home.tsx +187 -0
- package/templates/expo/screens/SignIn.tsx +112 -0
- package/templates/expo/tsconfig.json +6 -0
- package/templates/expo/usebecky.template.json +36 -0
- package/templates/extension/README.md +128 -0
- package/templates/extension/_env.example +21 -0
- package/templates/extension/_gitignore +11 -0
- package/templates/extension/logo.svg +1 -0
- package/templates/extension/package.json +25 -0
- package/templates/extension/src/accounts.ts +90 -0
- package/templates/extension/src/app.ts +178 -0
- package/templates/extension/src/pages.ts +108 -0
- package/templates/extension/src/replay-guard.ts +17 -0
- package/templates/extension/src/server.ts +57 -0
- package/templates/extension/src/settings.ts +69 -0
- package/templates/extension/src/ui.ts +70 -0
- package/templates/extension/test/app.test.ts +222 -0
- package/templates/extension/tsconfig.json +16 -0
- package/templates/extension/usebecky-extension.json +36 -0
- package/templates/extension/usebecky.template.json +22 -0
- package/templates/landing/README.md +43 -0
- package/templates/landing/_env.example +4 -0
- package/templates/landing/_gitignore +9 -0
- package/templates/landing/index.html +16 -0
- package/templates/landing/package.json +28 -0
- package/templates/landing/public/icon.svg +1 -0
- package/templates/landing/src/App.tsx +97 -0
- package/templates/landing/src/components/Contact.tsx +43 -0
- package/templates/landing/src/components/Counter.tsx +34 -0
- package/templates/landing/src/components/Feedback.tsx +36 -0
- package/templates/landing/src/components/Logo.tsx +11 -0
- package/templates/landing/src/components/Receipt.tsx +128 -0
- package/templates/landing/src/components/Setup.tsx +20 -0
- package/templates/landing/src/components/fields.tsx +63 -0
- package/templates/landing/src/content.ts +22 -0
- package/templates/landing/src/index.css +119 -0
- package/templates/landing/src/lib/usebecky.ts +11 -0
- package/templates/landing/src/lib/waitlist.ts +46 -0
- package/templates/landing/src/main.tsx +12 -0
- package/templates/landing/src/vite-env.d.ts +6 -0
- package/templates/landing/tsconfig.json +19 -0
- package/templates/landing/usebecky.template.json +20 -0
- package/templates/landing/vite.config.ts +10 -0
- package/templates/notes/README.md +68 -0
- package/templates/notes/_env.example +4 -0
- package/templates/notes/_gitignore +9 -0
- package/templates/notes/index.html +15 -0
- package/templates/notes/package.json +28 -0
- package/templates/notes/public/icon.svg +1 -0
- package/templates/notes/src/App.tsx +35 -0
- package/templates/notes/src/brand.ts +7 -0
- package/templates/notes/src/components/Composer.tsx +113 -0
- package/templates/notes/src/components/NoteEntry.tsx +151 -0
- package/templates/notes/src/components/Notes.tsx +163 -0
- package/templates/notes/src/components/Setup.tsx +44 -0
- package/templates/notes/src/components/SignIn.tsx +112 -0
- package/templates/notes/src/components/icons.tsx +54 -0
- package/templates/notes/src/index.css +105 -0
- package/templates/notes/src/lib/notes.ts +68 -0
- package/templates/notes/src/lib/usebecky.ts +9 -0
- package/templates/notes/src/main.tsx +22 -0
- package/templates/notes/src/vite-env.d.ts +6 -0
- package/templates/notes/tsconfig.json +19 -0
- package/templates/notes/usebecky.template.json +34 -0
- package/templates/notes/vite.config.ts +10 -0
- package/templates/saas/README.md +69 -0
- package/templates/saas/_env.example +10 -0
- package/templates/saas/_gitignore +11 -0
- package/templates/saas/app/(app)/account/ManageBilling.tsx +26 -0
- package/templates/saas/app/(app)/account/page.tsx +71 -0
- package/templates/saas/app/(app)/dashboard/Projects.tsx +227 -0
- package/templates/saas/app/(app)/dashboard/page.tsx +21 -0
- package/templates/saas/app/(app)/layout.tsx +29 -0
- package/templates/saas/app/(app)/premium/page.tsx +62 -0
- package/templates/saas/app/auth/callback/page.tsx +33 -0
- package/templates/saas/app/globals.css +143 -0
- package/templates/saas/app/icon.svg +1 -0
- package/templates/saas/app/layout.tsx +20 -0
- package/templates/saas/app/page.tsx +87 -0
- package/templates/saas/app/pricing/Plans.tsx +133 -0
- package/templates/saas/app/pricing/TestCardHint.tsx +18 -0
- package/templates/saas/app/pricing/page.tsx +21 -0
- package/templates/saas/app/setup/page.tsx +34 -0
- package/templates/saas/app/sign-in/SignInForm.tsx +195 -0
- package/templates/saas/app/sign-in/page.tsx +21 -0
- package/templates/saas/brand.ts +10 -0
- package/templates/saas/components/AppNav.tsx +45 -0
- package/templates/saas/components/Logo.tsx +22 -0
- package/templates/saas/components/SiteHeader.tsx +50 -0
- package/templates/saas/components/Status.tsx +15 -0
- package/templates/saas/lib/session.ts +26 -0
- package/templates/saas/lib/usebecky.ts +11 -0
- package/templates/saas/next-env.d.ts +5 -0
- package/templates/saas/next.config.ts +5 -0
- package/templates/saas/package.json +26 -0
- package/templates/saas/postcss.config.mjs +3 -0
- package/templates/saas/tsconfig.json +21 -0
- package/templates/saas/usebecky.template.json +31 -0
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
# Access rules (Row Level Security)
|
|
2
|
+
|
|
3
|
+
Every request runs inside Postgres as one of three roles, with the caller's token claims available to SQL:
|
|
4
|
+
|
|
5
|
+
| Caller | Role | `auth.uid()` |
|
|
6
|
+
|---|---|---|
|
|
7
|
+
| Publishable key, nobody signed in | `anon` | `null` |
|
|
8
|
+
| Publishable key + user access token (the SDK sends it automatically) | `authenticated` | the user's id |
|
|
9
|
+
| Secret key (server only), or `baas.admin` | `service_role` | `null`; bypasses RLS |
|
|
10
|
+
|
|
11
|
+
A user token always wins over the key's role, so `baas.as(req)` on the server (secret key + user token) runs as `authenticated` with RLS.
|
|
12
|
+
|
|
13
|
+
New tables in `public` get RLS enabled automatically by an event trigger. RLS with no policy denies everything to `anon` and `authenticated`: reads return `[]`, inserts fail with `permission_denied`, and updates and deletes match no rows (no error, nothing changes). Policies are permissive and combine with OR: a row is allowed if any policy for that command and role allows it.
|
|
14
|
+
|
|
15
|
+
## Helper functions (exist in every project)
|
|
16
|
+
|
|
17
|
+
| Function | Returns | Use |
|
|
18
|
+
|---|---|---|
|
|
19
|
+
| `auth.uid()` | `uuid` or null | owner checks: `user_id = auth.uid()` |
|
|
20
|
+
| `auth.jwt()` | `jsonb` claims: `sub`, `role`, `email`, `aal`, `session_id`, `app_metadata`, `user_metadata`, `is_anonymous` | `auth.jwt() ->> 'aal' = 'aal2'`, `auth.jwt() -> 'app_metadata' ->> 'role'` |
|
|
21
|
+
| `auth.role()` | `'anon'`, `'authenticated'` or `'service_role'` | rarely needed; prefer `to <role>` |
|
|
22
|
+
| `auth.email()` | `text` | invitations by email |
|
|
23
|
+
| `billing.has_access(feature text)` | `boolean` | true when the signed-in user has an active, trialing or in-grace past_due subscription, or a paid purchase, for a product whose key equals `feature` or whose `features` contain it |
|
|
24
|
+
| `billing.has_purchased(product_key text)` | `boolean` | true for a paid (not refunded) purchase of that product, or a subscription to it that currently grants access |
|
|
25
|
+
| `storage.foldername(name text)` | `text[]` | `'a/b/c.png'` → `{a,b}`; `(storage.foldername(name))[1]` is the top folder |
|
|
26
|
+
| `storage.filename(name text)` | `text` | `'a/b/c.png'` → `'c.png'` |
|
|
27
|
+
| `storage.extension(name text)` | `text` | `'a/b/c.PNG'` → `'png'` (lowercase, `''` if none) |
|
|
28
|
+
|
|
29
|
+
`billing.has_access(uid uuid, feature text)` and `billing.has_purchased(uid uuid, product_key text)` also exist but only `service_role` and the project owner may call them (SQL editor, server). In policies use the one-argument forms.
|
|
30
|
+
|
|
31
|
+
## Policy anatomy
|
|
32
|
+
|
|
33
|
+
```sql
|
|
34
|
+
create policy "Users update own notes" on public.notes -- a readable name, then the table
|
|
35
|
+
for update -- select | insert | update | delete | all
|
|
36
|
+
to authenticated -- anon | authenticated | anon, authenticated
|
|
37
|
+
using ((select auth.uid()) = user_id) -- which existing rows are visible / affected (select, update, delete)
|
|
38
|
+
with check ((select auth.uid()) = user_id); -- what new or changed rows must satisfy (insert, update)
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
- `insert` takes only `with check`; `select` and `delete` take only `using`; `update` takes both (usually the same rule).
|
|
42
|
+
- Wrap `auth.uid()` as `(select auth.uid())` in large tables: Postgres evaluates it once per query instead of once per row. Index the owner column.
|
|
43
|
+
- `upsert` needs INSERT and UPDATE policies (plus SELECT to return rows). `upsert(..., { ignoreDuplicates: true })` needs only INSERT.
|
|
44
|
+
- `.insert(...).select()` also needs a SELECT policy that lets the user see the new row.
|
|
45
|
+
- An UPDATE blocked by `using` changes 0 rows without an error; one blocked by `with check` returns `permission_denied`.
|
|
46
|
+
- Drop and recreate to change a policy: `drop policy "name" on public.notes;`.
|
|
47
|
+
|
|
48
|
+
## Where to run SQL
|
|
49
|
+
|
|
50
|
+
| What | Where |
|
|
51
|
+
|---|---|
|
|
52
|
+
| Tables, columns, indexes, policies on `public` tables, functions, views | A migration: `npx usebecky db new <name>`, write the SQL in `usebecky/migrations/`, `npx usebecky db push` (runs as the project owner, all files in one transaction). The dashboard's SQL editor runs the same SQL by hand |
|
|
53
|
+
| Table plus standard policies in one click | Dashboard → Database → Tables, presets `owner`, `public_read`, `authenticated`, `private` |
|
|
54
|
+
| Policies on `storage.objects` (file access) | `presets` of the bucket in `usebecky/config.json`, then `npx usebecky config push` (or Dashboard → Storage → bucket, also for a custom policy). Migrations cannot alter `storage.objects`. |
|
|
55
|
+
| Enable realtime on a table | `realtime.tables` in `usebecky/config.json`, then `npx usebecky config push` |
|
|
56
|
+
| Triggers on `auth.users` | Not available (only project templates add one, for `profiles`) |
|
|
57
|
+
|
|
58
|
+
Write the SQL as a migration file and apply it yourself with `npx usebecky db push` (`--dry-run` first). Never ask the user to paste it into the SQL editor.
|
|
59
|
+
|
|
60
|
+
## Recipes
|
|
61
|
+
|
|
62
|
+
### 1. Private rows: each user sees only their own
|
|
63
|
+
|
|
64
|
+
```sql
|
|
65
|
+
create table public.todos (
|
|
66
|
+
id uuid primary key default gen_random_uuid(),
|
|
67
|
+
user_id uuid not null default auth.uid() references auth.users (id) on delete cascade,
|
|
68
|
+
title text not null,
|
|
69
|
+
done boolean not null default false,
|
|
70
|
+
created_at timestamptz not null default now()
|
|
71
|
+
);
|
|
72
|
+
create index on public.todos (user_id);
|
|
73
|
+
alter table public.todos enable row level security;
|
|
74
|
+
create policy "Users read own todos" on public.todos for select to authenticated using ((select auth.uid()) = user_id);
|
|
75
|
+
create policy "Users add own todos" on public.todos for insert to authenticated with check ((select auth.uid()) = user_id);
|
|
76
|
+
create policy "Users update own todos" on public.todos for update to authenticated using ((select auth.uid()) = user_id) with check ((select auth.uid()) = user_id);
|
|
77
|
+
create policy "Users delete own todos" on public.todos for delete to authenticated using ((select auth.uid()) = user_id);
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
Client: `baas.from('todos').insert({ title })`. Do not send `user_id`; the default fills it and `with check` rejects anyone else's id.
|
|
81
|
+
|
|
82
|
+
### 2. Public read, owner write (blog posts, listings)
|
|
83
|
+
|
|
84
|
+
```sql
|
|
85
|
+
create policy "Anyone reads published posts" on public.posts for select to anon, authenticated using (published or (select auth.uid()) = user_id);
|
|
86
|
+
create policy "Authors add posts" on public.posts for insert to authenticated with check ((select auth.uid()) = user_id);
|
|
87
|
+
create policy "Authors edit posts" on public.posts for update to authenticated using ((select auth.uid()) = user_id) with check ((select auth.uid()) = user_id);
|
|
88
|
+
create policy "Authors delete posts" on public.posts for delete to authenticated using ((select auth.uid()) = user_id);
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
### 3. Profiles: readable by signed-in users, editable by their owner
|
|
92
|
+
|
|
93
|
+
```sql
|
|
94
|
+
create table public.profiles (
|
|
95
|
+
id uuid primary key references auth.users (id) on delete cascade,
|
|
96
|
+
display_name text,
|
|
97
|
+
avatar_url text,
|
|
98
|
+
updated_at timestamptz not null default now()
|
|
99
|
+
);
|
|
100
|
+
alter table public.profiles enable row level security;
|
|
101
|
+
create policy "Signed-in users read profiles" on public.profiles for select to authenticated using (true);
|
|
102
|
+
create policy "Users create their profile" on public.profiles for insert to authenticated with check (id = (select auth.uid()));
|
|
103
|
+
create policy "Users update their profile" on public.profiles for update to authenticated using (id = (select auth.uid())) with check (id = (select auth.uid()));
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
Create the row after sign-in: `baas.from('profiles').upsert({ id: user.id, display_name }, { onConflict: 'id', ignoreDuplicates: true })`. Reference `public.profiles (id)` from other tables when you want to embed author names (`select('*, author:profiles(display_name)')`).
|
|
107
|
+
|
|
108
|
+
### 4. Teams / organizations (membership table)
|
|
109
|
+
|
|
110
|
+
Policies that query the table they protect recurse. Put the membership check in a `security definer` function owned by you (the project owner bypasses RLS on its own tables). The `team` project template (`templates.md`) is a complete, tested version of this pattern with roles, invites and a last-owner guard.
|
|
111
|
+
|
|
112
|
+
```sql
|
|
113
|
+
create table public.teams (id uuid primary key default gen_random_uuid(), name text not null, created_at timestamptz not null default now());
|
|
114
|
+
create table public.team_members (
|
|
115
|
+
team_id uuid not null references public.teams (id) on delete cascade,
|
|
116
|
+
user_id uuid not null references auth.users (id) on delete cascade,
|
|
117
|
+
role text not null default 'member' check (role in ('owner', 'member')),
|
|
118
|
+
primary key (team_id, user_id)
|
|
119
|
+
);
|
|
120
|
+
create index on public.team_members (user_id);
|
|
121
|
+
create table public.projects (
|
|
122
|
+
id uuid primary key default gen_random_uuid(),
|
|
123
|
+
team_id uuid not null references public.teams (id) on delete cascade,
|
|
124
|
+
name text not null
|
|
125
|
+
);
|
|
126
|
+
create index on public.projects (team_id);
|
|
127
|
+
alter table public.teams enable row level security;
|
|
128
|
+
alter table public.team_members enable row level security;
|
|
129
|
+
alter table public.projects enable row level security;
|
|
130
|
+
|
|
131
|
+
create function public.is_team_member(t uuid) returns boolean
|
|
132
|
+
language sql stable security definer set search_path = '' as $$
|
|
133
|
+
select exists (select 1 from public.team_members m where m.team_id = t and m.user_id = auth.uid())
|
|
134
|
+
$$;
|
|
135
|
+
create function public.is_team_owner(t uuid) returns boolean
|
|
136
|
+
language sql stable security definer set search_path = '' as $$
|
|
137
|
+
select exists (select 1 from public.team_members m where m.team_id = t and m.user_id = auth.uid() and m.role = 'owner')
|
|
138
|
+
$$;
|
|
139
|
+
revoke execute on function public.is_team_member(uuid), public.is_team_owner(uuid) from public, anon, authenticated;
|
|
140
|
+
grant execute on function public.is_team_member(uuid), public.is_team_owner(uuid) to authenticated;
|
|
141
|
+
|
|
142
|
+
create policy "Members read their teams" on public.teams for select to authenticated using (public.is_team_member(id));
|
|
143
|
+
create policy "Members see co-members" on public.team_members for select to authenticated using (public.is_team_member(team_id));
|
|
144
|
+
create policy "Owners add members" on public.team_members for insert to authenticated with check (public.is_team_owner(team_id));
|
|
145
|
+
create policy "Owners remove members" on public.team_members for delete to authenticated using (public.is_team_owner(team_id));
|
|
146
|
+
create policy "Members read team projects" on public.projects for select to authenticated using (public.is_team_member(team_id));
|
|
147
|
+
create policy "Members write team projects" on public.projects for all to authenticated using (public.is_team_member(team_id)) with check (public.is_team_member(team_id));
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
Creating a team and its first owner row is a two-table write the policies above do not allow for a brand-new team. Do it in one `security definer` function called with `baas.rpc('create_team', { team_name })`:
|
|
151
|
+
|
|
152
|
+
```sql
|
|
153
|
+
create function public.create_team(team_name text) returns uuid
|
|
154
|
+
language plpgsql security definer set search_path = '' as $$
|
|
155
|
+
declare new_id uuid;
|
|
156
|
+
begin
|
|
157
|
+
if auth.uid() is null then raise exception 'Sign in first'; end if;
|
|
158
|
+
insert into public.teams (name) values (team_name) returning id into new_id;
|
|
159
|
+
insert into public.team_members (team_id, user_id, role) values (new_id, auth.uid(), 'owner');
|
|
160
|
+
return new_id;
|
|
161
|
+
end $$;
|
|
162
|
+
revoke execute on function public.create_team(text) from public, anon, authenticated;
|
|
163
|
+
grant execute on function public.create_team(text) to authenticated;
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
A `raise exception` inside a function reaches the client as `error.code === 'raised_exception'` with your text in `error.message`.
|
|
167
|
+
|
|
168
|
+
### 5. Paid content (subscription or purchase)
|
|
169
|
+
|
|
170
|
+
```sql
|
|
171
|
+
-- Whole table for paying users (the saas template's premium_content and its `premium` feature)
|
|
172
|
+
create policy "Premium users read premium content" on public.premium_content for select to authenticated using (billing.has_access('premium'));
|
|
173
|
+
-- Free and premium rows in one table
|
|
174
|
+
create policy "Free lessons, or Pro" on public.lessons for select to anon, authenticated using (not premium or billing.has_access('pro'));
|
|
175
|
+
-- Writes limited to paying users
|
|
176
|
+
create policy "Pro users create boards" on public.boards for insert to authenticated with check ((select auth.uid()) = user_id and billing.has_access('pro'));
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
`'pro'` is a product key or a feature listed on a product (Dashboard → Payments). Trials and past_due subscriptions inside the grace period (default 3 days) count as access.
|
|
180
|
+
|
|
181
|
+
### 6. Buyers only (one-time purchases)
|
|
182
|
+
|
|
183
|
+
```sql
|
|
184
|
+
create policy "Anyone reads reviews" on public.reviews for select using (true);
|
|
185
|
+
create policy "Buyers review what they bought" on public.reviews for insert to authenticated
|
|
186
|
+
with check ((select auth.uid()) = user_id and billing.has_purchased(product_key));
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
### 7. Admins via `app_metadata`
|
|
190
|
+
|
|
191
|
+
Users cannot change `app_metadata` (only your server can), so it is safe for roles. Never authorize with `user_metadata`: users edit it with `auth.updateUser({ data })`.
|
|
192
|
+
|
|
193
|
+
```ts
|
|
194
|
+
// make-admin.ts: a Node script, server only (secret key). Run once: node --env-file=.env make-admin.ts
|
|
195
|
+
import { baas } from 'usebecky/server'
|
|
196
|
+
|
|
197
|
+
const userId = '0b6f3c2e-5d1a-4f7e-8c9b-2a1d3e4f5a6b' // Dashboard → Auth → Users
|
|
198
|
+
const { error } = await baas.auth.admin.updateUser(userId, { appMetadata: { role: 'admin' } })
|
|
199
|
+
if (error) console.error(error.message)
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
```sql
|
|
203
|
+
create policy "Admins read everything" on public.orders for select to authenticated
|
|
204
|
+
using ((auth.jwt() -> 'app_metadata' ->> 'role') = 'admin');
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
The new claim appears in the user's access token after the next refresh or sign-in.
|
|
208
|
+
|
|
209
|
+
### 8. Require two-factor authentication
|
|
210
|
+
|
|
211
|
+
```sql
|
|
212
|
+
create policy "Billing details need 2FA" on public.billing_details for select to authenticated
|
|
213
|
+
using ((select auth.uid()) = user_id and (auth.jwt() ->> 'aal') = 'aal2');
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
### 9. Anonymous insert-only (contact form, waitlist)
|
|
217
|
+
|
|
218
|
+
```sql
|
|
219
|
+
create policy "Anyone can join the waitlist" on public.waitlist for insert to anon, authenticated with check (true);
|
|
220
|
+
-- no select policy: nobody can read the list from the app; read it with the secret key on the server
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
Use `insert(...)` without `.select()` here, because the caller cannot read the row back.
|
|
224
|
+
|
|
225
|
+
### 10. Server-only table
|
|
226
|
+
|
|
227
|
+
Enable RLS and add no policy. Only `service_role` (`baas.admin`, secret key) can read or write it.
|
|
228
|
+
|
|
229
|
+
### 10b. Limit which columns users may set (column privileges)
|
|
230
|
+
|
|
231
|
+
Policies choose rows; grants choose columns. Combine them when users may change only some fields:
|
|
232
|
+
|
|
233
|
+
```sql
|
|
234
|
+
-- Customers may only cancel: the policy allows status = 'cancelled', the grant allows only the status column
|
|
235
|
+
create policy "Customers cancel their own bookings" on public.bookings for update to authenticated
|
|
236
|
+
using (user_id = auth.uid()) with check (user_id = auth.uid() and status = 'cancelled');
|
|
237
|
+
revoke update on public.bookings from anon, authenticated;
|
|
238
|
+
grant update (status) on public.bookings to authenticated;
|
|
239
|
+
|
|
240
|
+
-- Insert-only table where visitors may set only some columns (no reads, updates or deletes)
|
|
241
|
+
revoke all on public.waitlist from anon, authenticated;
|
|
242
|
+
grant insert (email, referral_code, referred_by) on public.waitlist to anon, authenticated;
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
Writing another column then fails with `permission_denied` ("The "authenticated" role is not allowed to update ..."). Expose aggregates without exposing rows through a `security definer` function such as `waitlist_count()` (see the `waitlist` template).
|
|
246
|
+
|
|
247
|
+
### 11. Files in storage (`storage.objects`)
|
|
248
|
+
|
|
249
|
+
Policies on `storage.objects` decide who can upload, download, list, overwrite and delete. Create them with the bucket presets in Dashboard → Storage, or with the platform policies API (`http-api.md`; its `using` / `check` fields take these expressions). Common rules (`name` is the path inside the bucket, `bucket_id` the bucket):
|
|
250
|
+
|
|
251
|
+
```text
|
|
252
|
+
-- user_folder preset: users manage files under "<their user id>/..."
|
|
253
|
+
bucket_id = 'avatars' and (storage.foldername(name))[1] = auth.uid()::text
|
|
254
|
+
-- public_read preset (to anon, authenticated)
|
|
255
|
+
bucket_id = 'avatars'
|
|
256
|
+
-- authenticated_read / authenticated_upload presets (to authenticated)
|
|
257
|
+
bucket_id = 'shared'
|
|
258
|
+
-- paid files (custom)
|
|
259
|
+
bucket_id = 'videos' and billing.has_access('pro')
|
|
260
|
+
-- only images (custom insert check)
|
|
261
|
+
bucket_id = 'avatars' and (storage.foldername(name))[1] = auth.uid()::text and storage.extension(name) in ('png', 'jpg', 'jpeg', 'webp')
|
|
262
|
+
```
|
|
263
|
+
|
|
264
|
+
Overwriting (`upsert: true`) needs SELECT and UPDATE policies as well as INSERT. Moving needs UPDATE on both paths; copying needs SELECT on the source and INSERT on the destination.
|
|
265
|
+
|
|
266
|
+
### 12. Functions called with `baas.rpc()`
|
|
267
|
+
|
|
268
|
+
Every function in `public` is callable through the API by everyone, `anon` included, by default (Postgres grants EXECUTE to `public`).
|
|
269
|
+
|
|
270
|
+
- Default `security invoker`: runs as the caller, RLS applies. Prefer this.
|
|
271
|
+
- `security definer`: runs as you (the table owner) and bypasses RLS. Pin `set search_path = ''` and schema-qualify every name, check `auth.uid()` inside, return only what the caller may see, and limit who can call it:
|
|
272
|
+
|
|
273
|
+
```sql
|
|
274
|
+
revoke execute on function public.create_team(text) from public, anon, authenticated;
|
|
275
|
+
grant execute on function public.create_team(text) to authenticated;
|
|
276
|
+
```
|
|
277
|
+
|
|
278
|
+
Revoking only from `anon` is not enough: the default grant to `public` still applies.
|
|
279
|
+
|
|
280
|
+
```sql
|
|
281
|
+
create function public.complete_all_todos() returns integer
|
|
282
|
+
language sql security invoker as $$
|
|
283
|
+
with done as (update public.todos set done = true where user_id = auth.uid() and not done returning 1)
|
|
284
|
+
select count(*)::int from done
|
|
285
|
+
$$;
|
|
286
|
+
```
|
|
287
|
+
|
|
288
|
+
### 13. Realtime
|
|
289
|
+
|
|
290
|
+
Table changes are delivered only for rows the subscriber can SELECT under these same policies. DELETE events are checked against the old row when it fits in a notification (about 8 KB); for larger rows, any SELECT policy that applies to the subscriber's role lets the primary key through. Broadcast and presence channels are not covered by RLS: anyone with the publishable key can join any channel name.
|
|
291
|
+
|
|
292
|
+
## Testing and debugging policies
|
|
293
|
+
|
|
294
|
+
1. List policies: `select policyname, cmd, roles, qual, with_check from pg_policies where schemaname = 'public' and tablename = 'todos';`
|
|
295
|
+
2. Check RLS is on: `select relname, relrowsecurity from pg_class where relname = 'todos';`
|
|
296
|
+
3. Test from the app as three callers: signed out, user A, user B. User B must not see or change A's rows.
|
|
297
|
+
4. Confirm rows exist with Dashboard → Database → Tables (bypasses RLS) or `baas.admin` in a server script.
|
|
298
|
+
5. Dashboard → Database → Advisor flags tables with RLS off, RLS without policies and missing foreign-key indexes.
|
|
299
|
+
|
|
300
|
+
Mistakes to avoid:
|
|
301
|
+
|
|
302
|
+
- `using (true)` on update/delete for `authenticated`: any user can change any row.
|
|
303
|
+
- Policies `to public` when you meant `to authenticated`: `public` includes `anon`.
|
|
304
|
+
- Trusting a `user_id` sent by the client without `with check ((select auth.uid()) = user_id)`.
|
|
305
|
+
- Disabling RLS, or moving queries to the secret key, to make a query "work".
|
|
306
|
+
- Forgetting the SELECT policy, then wondering why `.insert().select()` or realtime returns nothing.
|
|
307
|
+
- Recursive policies (a policy on `team_members` that selects from `team_members`): use a `security definer` helper function.
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
# Add-ons: Redis and MongoDB
|
|
2
|
+
|
|
3
|
+
Managed Redis 7 and MongoDB 7, one click each in Dashboard → Add-ons, on the **Business plan only** (Free and Pro: the enable call returns `402 plan_required`; tell the user to upgrade, don't work around it). Both are **server-only**: there is no SDK wrapper, no browser access, no access rules. Use the official clients (`ioredis` or `redis`, and `mongodb`) from server code with a connection string in an environment variable.
|
|
4
|
+
|
|
5
|
+
Default to the built-in Postgres (tables + access rules) for app data. For simple caching and rate limits prefer the built-in cache (`baas.cache`, `references/cache.md`): no connection string, no key prefix, same 512 MB. Use Redis for sessions, simple queues, counters, leaderboards and anything needing Redis data types. Use MongoDB only for schemaless documents or existing MongoDB/Mongoose code.
|
|
6
|
+
|
|
7
|
+
## Connection strings
|
|
8
|
+
|
|
9
|
+
The user copies them from Dashboard → Add-ons → card → **Reveal** into the server's `.env` (never `NEXT_PUBLIC_*`, never client code). Ask the user for them; don't invent hosts.
|
|
10
|
+
|
|
11
|
+
```dotenv
|
|
12
|
+
REDIS_URL=redis://p_<ref>:<password>@<host>:<port>
|
|
13
|
+
MONGODB_URI=mongodb://p_<ref>:<password>@<host>:<port>/p_<ref>?authSource=p_<ref>
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## Redis rules
|
|
17
|
+
|
|
18
|
+
- Every key and pub/sub channel must start with the project's prefix `p_<ref>:` (shown on the card). Anything else fails with `NOPERM`.
|
|
19
|
+
- With ioredis, set `keyPrefix` once and write short keys. `keyPrefix` does NOT apply to channel names: write the prefix in `subscribe`/`publish` yourself. `PSUBSCRIBE` only accepts the whole prefix pattern `p_<ref>:*`.
|
|
20
|
+
- Blocked: `KEYS`, `SCAN`, `FLUSHALL`, `FLUSHDB`, `CONFIG`, `SELECT`, `MONITOR`, `CLIENT LIST/KILL`, `SORT`, `RANDOMKEY`, `DBSIZE`, `PUBSUB`, `CLIENT TRACKING`, `MOVE`, `COPY`, and all Lua/functions (`EVAL`, `EVALSHA`, `FUNCTION`). So BullMQ and other Lua-based libraries don't work; use lists (`LPUSH` + `BRPOP` on a `duplicate()` connection) for queues and `MULTI` + `INCR` + `EXPIRE ... NX` for rate limits. Keep key names in a set if you need to list them.
|
|
21
|
+
- Memory quota: Business 512 MB per project, measured by sampling. Over the limit writes keep working but the dashboard flags it; set TTLs on cache keys.
|
|
22
|
+
|
|
23
|
+
```ts
|
|
24
|
+
// lib/redis.ts (server only)
|
|
25
|
+
import { Redis } from 'ioredis'
|
|
26
|
+
|
|
27
|
+
export const redis = new Redis(process.env.REDIS_URL!, { keyPrefix: 'p_abc123def456:' })
|
|
28
|
+
|
|
29
|
+
// Cache a value for 5 minutes
|
|
30
|
+
export async function cacheHomePage(data: unknown) {
|
|
31
|
+
await redis.set('cache:home', JSON.stringify(data), 'EX', 300)
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// Rate limit: at most 10 attempts per user per minute
|
|
35
|
+
export async function checkRateLimit(userId: string) {
|
|
36
|
+
const [[, count]] = (await redis.multi().incr(`rl:${userId}`).expire(`rl:${userId}`, 60, 'NX').exec()) as [[null, number]]
|
|
37
|
+
if (count > 10) throw new Error('Too many attempts')
|
|
38
|
+
}
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## MongoDB rules
|
|
42
|
+
|
|
43
|
+
- One database `p_<ref>` (in the connection string, so `client.db()` with no name opens it). The user has `readWrite` there only: no other databases, no `createUser`, no `listDatabases` of others.
|
|
44
|
+
- No server-side JavaScript: `$where`, `$function`, `$accumulator`, `mapReduce` are disabled.
|
|
45
|
+
- Storage quota: Business 10 GB (`dataSize + indexSize`), the team's total across its projects. Over the limit the user can only read and delete (inserts/updates fail with `not authorized`) until usage drops; deleting documents lowers usage right away.
|
|
46
|
+
- Never pass request bodies straight into filters (`find(req.body)` allows `{ "$ne": "" }` injection); pick fields and coerce types.
|
|
47
|
+
- In Next.js, cache the client on `globalThis` in development and import it only from server code (`import 'server-only'`).
|
|
48
|
+
|
|
49
|
+
```ts
|
|
50
|
+
// lib/mongodb.ts (server only)
|
|
51
|
+
import { MongoClient, ObjectId } from 'mongodb'
|
|
52
|
+
|
|
53
|
+
const client = new MongoClient(process.env.MONGODB_URI!)
|
|
54
|
+
export const db = client.db()
|
|
55
|
+
|
|
56
|
+
export async function addTodo(title: string) {
|
|
57
|
+
const { insertedId } = await db.collection('todos').insertOne({ title, done: false, createdAt: new Date() })
|
|
58
|
+
return insertedId.toHexString()
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export async function completeTodo(id: string) {
|
|
62
|
+
await db.collection('todos').updateOne({ _id: new ObjectId(id) }, { $set: { done: true } })
|
|
63
|
+
}
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
## Manage them in the dashboard
|
|
67
|
+
|
|
68
|
+
Enable, disable, rotate the password and reveal the connection string in Dashboard → Add-ons (there is no customer API or CLI for it). Disabling deletes ALL data: only suggest it when the user explicitly asks. The data viewer (Redis keys, MongoDB collections) is on the same page.
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
# Analytics reference
|
|
2
|
+
|
|
3
|
+
Visitor analytics for the developer's website or app: page views, time on page, scroll depth, outbound links, downloads, site search, Web Vitals, custom events, goals and funnels, shown in Dashboard → Analytics (Overview, Realtime, Traffic sources, Pages & events, Audience, Goals & funnels). Backend usage (requests, errors, sign-ups, revenue, storage) needs no code and is in Dashboard → Settings → Usage & plan → Backend activity, not in Analytics.
|
|
4
|
+
|
|
5
|
+
## Must-tell-the-user rules
|
|
6
|
+
|
|
7
|
+
1. **Analytics is OFF for every project until the owner turns it on**: Dashboard → Analytics → tick "I'll mention analytics in my privacy policy" → **Turn on analytics**. While off, nothing is stored (the API answers `202 {stored: 0, reason: "analytics_off"}`), so adding code alone shows nothing. Always tell the user to turn it on.
|
|
8
|
+
2. **Privacy policy duty**: whenever you add analytics, tell the user they must mention it in their privacy policy. A ready-to-copy paragraph is in the Analytics guide: https://usebecky.com/docs/guides/analytics (section "Mention analytics in your privacy policy"). The default privacy mode stores nothing on the device, so it is made to work without a cookie banner; local mode (`data-storage="local"` / `storage: 'local'`) usually needs consent in the EU/UK (see Consent below). Not legal advice.
|
|
9
|
+
3. Never put the secret key (`ub_sk_...`) in a website. The script and browser code use only the publishable key.
|
|
10
|
+
|
|
11
|
+
## Websites: the script tag
|
|
12
|
+
|
|
13
|
+
One tag in the `<head>` of every page. Prefer running the CLI in the website's folder; it detects the framework, inserts the tag once, prints what changed, and never touches the secret key:
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
npx usebecky analytics # key + URL from the env file `npx usebecky init` wrote, or asks
|
|
17
|
+
npx usebecky analytics --dry-run # preview
|
|
18
|
+
npx usebecky analytics --key ub_pk_... --api-url https://<project-url>
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Targets: `index.html` (plain HTML: every root `.html`; Vite; `public/index.html` for CRA/Vue CLI; `src/index.html` for Angular), Next.js App Router (`app/layout.tsx`, `next/script` with `strategy="afterInteractive"`), Next.js Pages Router (`pages/_document`), Astro layouts (`is:inline`), SvelteKit `src/app.html`, Nuxt `nuxt.config` (`app.head.script`), Remix / React Router `app/root.tsx`. Unknown setups get the tag printed with where to paste it.
|
|
22
|
+
|
|
23
|
+
The tag (the same string Dashboard → Analytics shows):
|
|
24
|
+
|
|
25
|
+
```html
|
|
26
|
+
<script defer src="https://<project-url>/analytics/v1/script.js" data-key="ub_pk_..."></script>
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
```tsx
|
|
30
|
+
// app/layout.tsx (Next.js App Router)
|
|
31
|
+
import Script from 'next/script'
|
|
32
|
+
import type { ReactNode } from 'react'
|
|
33
|
+
|
|
34
|
+
export default function RootLayout({ children }: { children: ReactNode }) {
|
|
35
|
+
return (
|
|
36
|
+
<html lang="en">
|
|
37
|
+
<body>
|
|
38
|
+
{children}
|
|
39
|
+
<Script src="https://<project-url>/analytics/v1/script.js" data-key="ub_pk_..." strategy="afterInteractive" />
|
|
40
|
+
</body>
|
|
41
|
+
</html>
|
|
42
|
+
)
|
|
43
|
+
}
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
Website builders: WordPress (WPCode plugin → Header), Wix (Settings → Custom code → All pages, Head), Webflow (Site settings → Custom code → Head code), Shopify (`layout/theme.liquid` before `</head>`), Squarespace (Code Injection → Header).
|
|
47
|
+
|
|
48
|
+
What the script does by itself: `$pageview` on load and on SPA navigation (pushState / replaceState / popstate; a change after `?` or `#` only is not a new page), `$engagement` when a page is left or hidden (`engaged_ms` visible time since the last one, `scroll_pct`, and once per page view `lcp_ms`, `inp_ms`, `cls` where the browser measures them), `$outbound` (`props.url`, no query string), `$download` (`props.url`, `props.ext`; pdf, zip, dmg, exe, csv, xlsx, docx, pptx, mp3, mp4, ... or `download` attribute), `$search` (`props.term` from `?q=`, `s`, `search`, `query`). Sends nothing for bots / headless / `navigator.webdriver`, Do Not Track or Global Privacy Control, or after opt-out. Never throws; about 3 KB gzipped; batches and uses `sendBeacon`.
|
|
49
|
+
|
|
50
|
+
Attributes: `data-key` (required), `data-api` (default: the script's origin), `data-auto="false"` (no automatic page views), `data-respect-dnt="false"`, `data-outbound="false"`, `data-downloads="false"`, `data-search-params="k,keyword"` (`"false"` = off), `data-debug` (console log of every event or why nothing is sent), `data-storage="local"` (opt-in local mode, see below).
|
|
51
|
+
|
|
52
|
+
**Privacy mode (default)**: no cookies, nothing stored on the device (only the opt-out, when the visitor opts out), no visitor/visit id, timezone or screen size sent. The server recognizes a visitor for one UTC day (`h:` + HMAC of a daily random salt, IP, user agent, hostname; salts deleted after their day) and continues a visit for 30 idle minutes. New vs returning and retention can't count these visits (the dashboard shows a note); signed-in visits (SDK with usebecky auth) are always followed by their user. **Remember returning visitors (consent)**: turn on Analytics → Settings → Returning visitors, then call `usebecky('consent', true)` (script) or `baas.analytics.consent(true)` (SDK) from the consent banner; only then a random id is kept in localStorage (13 months; `consent(false)` deletes it), with timezone, language and screen size bucket. `data-consent="true"` on the tag = already agreed. **Local mode** (`data-storage="local"`): the older switch, remembers everyone without the project setting; only load it after consent.
|
|
53
|
+
|
|
54
|
+
Do not combine the script with the SDK's `autoPageviews: true` (or manual `baas.analytics.page()` calls) on the same pages: page views would be counted twice. The script and the SDK share the visitor and the visit (privacy mode: the same server-made id from IP + user agent + hostname; local mode: localStorage keys `ub-<ref>-anon-id`, `ub-<ref>-session`, `ub-<ref>-first-seen`) and the opt-out (`ub-<ref>-analytics-optout`), so the script for page views plus `baas.analytics.track()` for app events is fine. Use the same mode in both.
|
|
55
|
+
|
|
56
|
+
## Custom events
|
|
57
|
+
|
|
58
|
+
```html
|
|
59
|
+
<!-- No code: every click sends the event; data-ub-prop-* become props -->
|
|
60
|
+
<button data-ub-event="signup_clicked" data-ub-prop-plan="pro">Sign up</button>
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
```js
|
|
64
|
+
// Script API: the script tag defines window.usebecky
|
|
65
|
+
usebecky.track('added_to_cart', { product: 'Blue mug', price: 12 })
|
|
66
|
+
usebecky.page('/checkout/step-2') // manual page view (with data-auto="false", or virtual pages)
|
|
67
|
+
usebecky.optOut() // stop counting this browser (remembered); usebecky.optIn() undoes it
|
|
68
|
+
usebecky('consent', true) // visitor agreed to be remembered (needs "Remember returning visitors"); false forgets
|
|
69
|
+
usebecky('notFound') // mark a 404 view in a single-page app (static 404 page: <meta name="usebecky:status" content="404">)
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Before the deferred script has loaded, queue calls in an inline script; the script runs them once it loads:
|
|
73
|
+
|
|
74
|
+
```html
|
|
75
|
+
<script>
|
|
76
|
+
window.usebecky = window.usebecky || { q: [] }
|
|
77
|
+
usebecky.q.push(['track', 'newsletter_form_shown'])
|
|
78
|
+
</script>
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
Names: `snake_case`, past tense, 1–100 characters, not starting with `$` (reserved: `$pageview`, `$identify`, `$engagement`, `$outbound`, `$download`, `$search`). Props: a JSON object up to 4 KB. Invalid input is dropped with one console warning. Never put personal data (emails, names) in props.
|
|
82
|
+
|
|
83
|
+
## SDK (apps whose code you write: React, Next.js, Expo, Node)
|
|
84
|
+
|
|
85
|
+
```ts
|
|
86
|
+
// src/lib/usebecky.ts (Vite; Next.js reads process.env.NEXT_PUBLIC_USEBECKY_URL / _PUBLISHABLE_KEY)
|
|
87
|
+
import { createClient } from 'usebecky'
|
|
88
|
+
|
|
89
|
+
export const baas = createClient(import.meta.env.VITE_USEBECKY_URL, import.meta.env.VITE_USEBECKY_PUBLISHABLE_KEY, {
|
|
90
|
+
analytics: {
|
|
91
|
+
autoPageviews: true, // page view on load + every history change (browser only). Default false. Not together with the script.
|
|
92
|
+
respectDoNotTrack: true, // default true
|
|
93
|
+
// enabled: false, // start off (cookie consent); call baas.analytics.enable() later
|
|
94
|
+
// storage: 'none', // privacy mode, the default in browsers; 'local' keeps a visitor id (default in React Native / Node)
|
|
95
|
+
// flushInterval: 5000, batchSize: 20 (max 50), maxQueueSize: 500, sessionTimeoutMinutes: 30
|
|
96
|
+
},
|
|
97
|
+
})
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
```ts
|
|
101
|
+
// inside an async function:
|
|
102
|
+
baas.analytics.track('signed_up', { plan: 'free' }) // never throws; batched; signed-in user attached automatically
|
|
103
|
+
baas.analytics.page() // browser: current path, title, referrer → "$pageview"
|
|
104
|
+
baas.analytics.page('/pricing') // Node / React Native: pass the path
|
|
105
|
+
baas.analytics.identify({ plan: 'pro' }) // traits for the signed-in user ("$identify", not in reports)
|
|
106
|
+
await baas.analytics.flush() // send now (before a Node process exits); data: { sent }
|
|
107
|
+
baas.analytics.disable() // opt out (shared with the script's optOut)
|
|
108
|
+
baas.analytics.enable() // opt back in / start after consent
|
|
109
|
+
baas.analytics.consent(true) // remember this visitor (project setting on); consent(false) forgets
|
|
110
|
+
baas.analytics.reset() // new anonymous id + session (shared computer, after sign-out)
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
The SDK also sends the landing page's UTM tags in a browser; in local mode (React Native, or `storage: 'local'`) also `language`, `timezone`, `screen_size` and `is_new_visitor`. Native apps: `references/ios.md`, `references/android.md` (`baas.analytics.screen(...)`, `track(...)`).
|
|
114
|
+
|
|
115
|
+
## Consent and privacy
|
|
116
|
+
|
|
117
|
+
- No cookies; IP addresses are never stored (used in memory only for the rate limit, the country lookup and the privacy-mode daily hash). Paths and referrers lose their query string except the five UTM tags. Privacy mode (default) stores nothing on the device; local mode keeps visitor ids in localStorage.
|
|
118
|
+
- EU/UK consent: needed for local mode (and if the user prefers to ask anyway): load the script only after "Accept" (cookie banner tool's Analytics/Statistics category, or inject the `<script>` with `document.createElement('script')` + `script.dataset.key = 'ub_pk_...'` on consent). SDK: `analytics: { enabled: false }` then `baas.analytics.enable()`. Never tell the user consent is legally unnecessary; say privacy mode is designed to work without a cookie banner and point to the guide's "What the law says" section.
|
|
119
|
+
- Per-project switches in Dashboard → Analytics → Settings → What we collect: `collect_country` (default true, also gates `timezone`), `collect_city` (false), `collect_language` (true), `collect_utm` (true). Allowed websites (`allowed_hosts`, ≤ 20, `*.example.com` allowed; empty = any) drop visits sent from other sites.
|
|
120
|
+
- Data kept by plan: Free 7 days, Pro 90 days, Business 13 months. Reports for older ranges → `403 plan_required`.
|
|
121
|
+
- Deleting a user deletes their `$identify` events and removes their user id from the others. Events live in `analytics.events` in the project DB; the publishable key can't read it; the owner can query it in the SQL editor.
|
|
122
|
+
|
|
123
|
+
## Goals and funnels
|
|
124
|
+
|
|
125
|
+
Goals (Dashboard → Analytics → Goals & funnels → Add a goal, ≤ 20): "Someone visits a page" (`type: 'page'`, `match` a path, trailing `*` = the section, `/blog/*`) or "Someone does an action" (`type: 'event'`, `match` an event name). Conversions = visits that reached a goal.
|
|
126
|
+
|
|
127
|
+
Funnels (Dashboard → Analytics → Goals & funnels → Add a funnel): ordered steps like a page view of `/pricing`, then the event `signed_up`, then `bought_pro`; each step shows users, conversion from the first and the previous step, and drop-off. Goals go in `usebecky/config.json` (`"analytics": {"enabled": true, "goals": [{"id": "signup", "name": "Signed up", "type": "event", "match": "signed_up"}, {"id": "pricing", "name": "Saw pricing", "type": "page", "match": "/pricing"}]}`, also `allowed_hosts`); run `npx usebecky config push` yourself. Funnels are set up only in the dashboard: tell the user which steps to add. Make the app send the events with `baas.analytics.track(...)` or `data-ub-event`.
|
|
128
|
+
|
|
129
|
+
## Reports
|
|
130
|
+
|
|
131
|
+
Reports (overview, realtime, pages, sources, channels, campaigns, countries, devices, events, outbound links, downloads, searches, retention, web vitals, goals) are in Dashboard → Analytics, with date ranges, comparison and filters. Channels: `direct`, `organic_search`, `social`, `email`, `paid`, `referral`. **Check my website** there verifies that the live page has the tag.
|
|
132
|
+
|
|
133
|
+
The same reports from your server (secret key, never in a browser), e.g. to show each customer of a platform their own site's numbers:
|
|
134
|
+
|
|
135
|
+
```ts
|
|
136
|
+
// stats.ts: server only (secret key)
|
|
137
|
+
import { baas } from 'usebecky/server'
|
|
138
|
+
|
|
139
|
+
const site = { filters: { hostname: 'shop.example.com' } } // one website of the project; leave out for all
|
|
140
|
+
const { data: overview } = await baas.analytics.overview({ range: '30d', ...site }) // kpis.visitors.value, series [{ t, visitors, ... }]
|
|
141
|
+
const { data: pages } = await baas.analytics.report('pages', { range: '30d', ...site, limit: 10 }) // rows [{ value: '/blog', pageviews, visitors, ... }]
|
|
142
|
+
const { data: sources } = await baas.analytics.report('sources', { range: '30d', ...site })
|
|
143
|
+
const { data: chart } = await baas.analytics.timeseries({ range: '30d', metric: 'visitors', dimension: 'devices', ...site })
|
|
144
|
+
console.log(overview?.kpis.visitors.value, pages?.rows.length, sources?.next_cursor, chart?.series.length)
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
- Period: `range` (`today`, `yesterday`, `7d`, `30d` default, `90d`, `12m`, `24m`) or `from`/`to` (dates, both included), `tz`, `compare: true` (numbers become `{ value, previous }`).
|
|
148
|
+
- Filters (exact, per visit; an array means "any of"): `hostname`, `country`, `region`, `city`, `source`, `channel`, `campaign`, `medium`, `page`, `landing_page`, `device`, `browser`, `os`, `language`, `event`.
|
|
149
|
+
- `report(dimension)`: `pages`, `landing_pages`, `exit_pages`, `sources`, `referrers`, `channels`, `campaigns`, `mediums`, `countries`, `regions`, `cities`, `languages`, `devices`, `browsers`, `os`, `screen_sizes`, `visitor_types`, `hostnames`, `events`, `outbound_links`, `downloads`, `searches`, `not_found`; options `limit` (1–100), `sort`, `dir`, `search`, `cursor` (= `next_cursor`).
|
|
150
|
+
- The plan's history limit applies (`plan_required`). Cache the answers a few minutes (`baas.cache.getOrSet`) when many customers open their stats. HTTP: `GET /analytics/v1/overview`, `/reports?dimension=`, `/timeseries` with the secret key.
|
|
151
|
+
|
|
152
|
+
## HTTP ingest (non-JS apps)
|
|
153
|
+
|
|
154
|
+
```bash
|
|
155
|
+
curl -X POST "$USEBECKY_URL/analytics/v1/events" \
|
|
156
|
+
-H "apikey: $USEBECKY_PUBLISHABLE_KEY" \
|
|
157
|
+
-H "content-type: application/json" \
|
|
158
|
+
-d '{"events":[{"name":"signed_up","anonymous_id":"device-123","session_id":"s-1","props":{"plan":"free"}}]}'
|
|
159
|
+
# → {"accepted":1} (analytics off → 202 {"stored":0,"reason":"analytics_off"})
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
Up to 50 events per request. Send a user's access token as `Authorization: Bearer <token>` to link the user; a `user_id` field is only accepted with the secret key. Rate limit: 300 requests per minute per project and IP. Optional fields (invalid values are ignored, never a 400): `path`, `referrer`, `title`, `timestamp`, `language`, `timezone`, `screen_size` or `screen_width`, `is_new_visitor`, `hostname`, `utm_source`, `utm_medium`, `utm_campaign`, `utm_term`, `utm_content`, and on `$engagement`: `engaged_ms`, `scroll_pct`, `lcp_ms`, `inp_ms`, `cls`.
|
|
163
|
+
|
|
164
|
+
## Troubleshooting
|
|
165
|
+
|
|
166
|
+
Nothing in the dashboard: analytics still off (most common); the tag isn't on the published site (the dashboard's "Check my website"); the tester's browser blocks it (ad blocker, Brave / Global Privacy Control, Do Not Track); `allowed_hosts` excludes the site; a CSP without the project URL in `script-src` and `connect-src`; `data-key` holds a wrong key. Add `data-debug` to the tag and read the browser console. Hash routers (`/#/about`): `data-auto="false"` plus `usebecky.page(location.hash.slice(1))` on `hashchange`.
|