@lupinum/better-convex-agents 0.1.0 → 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 (54) hide show
  1. package/dist/agent/AGENTS.md +6 -3
  2. package/dist/agent/pages/docs/build/application-behavior/error-handling.md +40 -1
  3. package/dist/agent/pages/docs/build/authentication/account-deletion.md +73 -0
  4. package/dist/agent/pages/docs/build/authentication/backend-authorization.md +6 -1
  5. package/dist/agent/pages/docs/build/authentication/better-auth-setup.md +3 -1
  6. package/dist/agent/pages/docs/build/authentication/sign-in-and-sign-out.md +3 -0
  7. package/dist/agent/pages/docs/build/authentication/transactional-email.md +45 -10
  8. package/dist/agent/pages/docs/build/files/private-downloads.md +126 -0
  9. package/dist/agent/pages/docs/build/files/storage-urls.md +8 -3
  10. package/dist/agent/pages/docs/build/files/upload-files.md +2 -2
  11. package/dist/agent/pages/docs/build/functions/limits-and-audit.md +142 -4
  12. package/dist/agent/pages/docs/build/functions/testing.md +24 -0
  13. package/dist/agent/pages/docs/build/queries/loading-and-stale-data.md +1 -1
  14. package/dist/agent/pages/docs/build/queries/pagination.md +2 -2
  15. package/dist/agent/pages/docs/build/queries/reactive-arguments.md +46 -0
  16. package/dist/agent/pages/docs/build/server/server-convex.md +16 -1
  17. package/dist/agent/pages/docs/build/write-data/concurrent-operations.md +1 -1
  18. package/dist/agent/pages/docs/build/write-data/forms.md +1 -1
  19. package/dist/agent/pages/docs/build/write-data/multi-step-operations.md +1 -1
  20. package/dist/agent/pages/docs/build/write-data/optimistic-updates.md +1 -1
  21. package/dist/agent/pages/docs/get-started/add-authentication.md +13 -3
  22. package/dist/agent/pages/docs/get-started/complete-and-delete.md +2 -0
  23. package/dist/agent/pages/docs/get-started/first-realtime-page.md +3 -1
  24. package/dist/agent/pages/docs/get-started/installation.md +3 -0
  25. package/dist/agent/pages/docs/get-started/next-steps.md +30 -0
  26. package/dist/agent/pages/docs/get-started/plain-vue.md +143 -41
  27. package/dist/agent/pages/docs/operations/before-launch.md +1 -1
  28. package/dist/agent/pages/docs/operations/log-streams.md +128 -0
  29. package/dist/agent/pages/docs/recipes/dynamic-query-list.md +1 -1
  30. package/dist/agent/pages/docs/recipes/error-messages.md +1 -1
  31. package/dist/agent/pages/docs/recipes/guest-users.md +67 -15
  32. package/dist/agent/pages/docs/recipes/multiple-file-uploads.md +1 -1
  33. package/dist/agent/pages/docs/recipes/optimistic-todo-list.md +1 -1
  34. package/dist/agent/pages/docs/recipes/realtime-feed.md +1 -1
  35. package/dist/agent/pages/docs/recipes/sign-in-link.md +129 -0
  36. package/dist/agent/pages/docs/reference/api-surface.md +11 -0
  37. package/dist/agent/pages/docs/reference/error-types.md +12 -2
  38. package/dist/agent/pages/docs/reference/operation-error-codes.md +15 -1
  39. package/dist/agent/pages/docs/reference/package-exports.md +3 -2
  40. package/dist/agent/pages/docs/reference/server-api.md +5 -1
  41. package/dist/index.d.mts +1 -1
  42. package/dist/index.d.ts +1 -1
  43. package/dist/index.mjs +1 -1
  44. package/dist/internal.d.mts +1 -1
  45. package/dist/internal.d.ts +1 -1
  46. package/dist/internal.mjs +1 -1
  47. package/dist/mcp.mjs +4 -2
  48. package/dist/shared/{better-convex-agents.DWStY2mj.mjs → better-convex-agents.BAvd6ID4.mjs} +475 -393
  49. package/dist/shared/{better-convex-agents.Jrci7p3C.d.mts → better-convex-agents.l5qUkNCR.d.mts} +14 -2
  50. package/dist/shared/{better-convex-agents.Jrci7p3C.d.ts → better-convex-agents.l5qUkNCR.d.ts} +14 -2
  51. package/dist/test.d.mts +1 -1
  52. package/dist/test.d.ts +1 -1
  53. package/dist/test.mjs +1 -1
  54. package/package.json +3 -3
@@ -84,6 +84,30 @@ Insert your app's own `users` row yourself, with `authId: 'ann'`. When the
84
84
  session was deleted, for example to test a sign-out, the next `signInAs`
85
85
  creates a session with a new ID.
86
86
 
87
+ The session expires one hour after `signInAs`, also in fake time. With
88
+ `vi.useFakeTimers()`, `t.finishAllScheduledFunctions(vi.runAllTimers)` runs
89
+ every timer, so it also moves the clock past the session's end, and the next
90
+ call is signed out. Move the clock in small steps instead, or give the session
91
+ a longer life. Pass `expiresInMs` on the first `signInAs` for that person in the
92
+ test: a later call reuses the live session and keeps its expiry.
93
+
94
+ ```ts
95
+ // Run the scheduled work of the next 10 seconds, one second at a time. Work
96
+ // that a step schedules starts in a later step, so take a few steps more than
97
+ // the time of the last job.
98
+ for (let step = 0; step < 12; step += 1) {
99
+ vi.advanceTimersByTime(1_000)
100
+ await t.finishInProgressScheduledFunctions()
101
+ }
102
+
103
+ // Or: a session that outlives a job scheduled 24 hours later.
104
+ const ann = await signInAs(t, 'ann', { expiresInMs: 7 * 24 * 60 * 60 * 1000 })
105
+ ```
106
+
107
+ The loop does not work for a scheduled action that awaits a timer itself, such
108
+ as `setTimeout`: the test waits for the action while the clock stands still. Use
109
+ `t.finishAllScheduledFunctions(vi.runAllTimers)` with a longer session there.
110
+
87
111
  ### Assert codes, not messages
88
112
 
89
113
  A refused call rejects with a `ConvexError` whose `data.code` says why:
@@ -37,7 +37,7 @@ A query with `server: false` is `idle` with `blockedBy === 'server'` during the
37
37
  ```vue
38
38
  <script setup lang="ts">
39
39
  import { api } from '#convex/api'
40
- import type { Id } from '~~/convex/_generated/dataModel'
40
+ import type { Id } from '#convex/dataModel'
41
41
 
42
42
  const props = defineProps<{
43
43
  organizationId: Id<'organizations'> | undefined
@@ -56,7 +56,7 @@ Do not pass `paginationOpts` from the component. The composable controls cursors
56
56
 
57
57
  ```vue
58
58
  <script setup lang="ts">
59
- import type { Id } from '~~/convex/_generated/dataModel'
59
+ import type { Id } from '#convex/dataModel'
60
60
  import { api } from '#convex/api'
61
61
 
62
62
  const props = defineProps<{ channelId: Id<'channels'> }>()
@@ -153,7 +153,7 @@ Use these [experimental helpers](../../reference/experimental.md) inside a mutat
153
153
  This example assumes message documents contain `_id`, `_creationTime`, `channelId`, and `body`. Include every document field when you insert an item. The temporary ID must not be used as a saved identifier.
154
154
 
155
155
  ```ts
156
- import type { Id } from '~~/convex/_generated/dataModel'
156
+ import type { Id } from '#convex/dataModel'
157
157
  import { api } from '#convex/api'
158
158
  import { insertAtTop } from '@lupinum/better-convex-nuxt/experimental'
159
159
 
@@ -46,6 +46,52 @@ When either input changes, the composable requests the new argument set.
46
46
 
47
47
  To send the same arguments to queries and mutations, see [Share arguments between calls](../write-data/mutations.md#share-arguments-between-calls).
48
48
 
49
+ ## Add a shared argument to every query
50
+
51
+ Some values go to many queries on many pages, for example the workspace that
52
+ the person selected. Pass the ref as a top-level field in each call. You do not
53
+ need a wrapper composable:
54
+
55
+ ```ts [app/composables/useWorkspaceId.ts]
56
+ import type { Id } from '#convex/dataModel'
57
+
58
+ export const useWorkspaceId = () => useState<Id<'workspaces'> | undefined>('workspaceId')
59
+ ```
60
+
61
+ ```ts
62
+ const workspaceId = useWorkspaceId()
63
+
64
+ const projects = useConvexQuery(api.projects.list, { workspaceId })
65
+ ```
66
+
67
+ When `workspaceId` changes, each query runs again with the new value. When the
68
+ ref holds `undefined`, Convex leaves the field out of the arguments. Declare the
69
+ field with `v.optional(...)` in the Convex function, and check in the function
70
+ that the person may read that workspace.
71
+
72
+ A wrapper that passes its arguments through unchanged keeps the argument types.
73
+ Type the parameters with `UseConvexQueryParameters`:
74
+
75
+ ```ts [app/composables/useAppQuery.ts]
76
+ import type {
77
+ UseConvexQueryParameters,
78
+ UseNuxtConvexQueryOptions,
79
+ } from '@lupinum/better-convex-nuxt'
80
+ import type { FunctionReference } from 'convex/server'
81
+
82
+ export function useAppQuery<Query extends FunctionReference<'query'>>(
83
+ query: Query,
84
+ ...parameters: UseConvexQueryParameters<Query, UseNuxtConvexQueryOptions>
85
+ ) {
86
+ // Your own code before the query, for example logging.
87
+ return useConvexQuery(query, ...parameters)
88
+ }
89
+ ```
90
+
91
+ A wrapper that adds a field to the arguments needs a type cast, because
92
+ TypeScript cannot check that the new object matches every query. Use a
93
+ top-level ref field instead.
94
+
49
95
  ## Keep the previous result deliberately
50
96
 
51
97
  With `keepPreviousData: true`:
@@ -13,7 +13,7 @@ source: "ginko-content"
13
13
 
14
14
  > Call Convex from a Nitro request with explicit authentication policy and request-scoped state.
15
15
 
16
- `serverConvex(event)` creates one request-scoped caller with `query`, `mutation`, and `action` methods.
16
+ `serverConvex(event)` creates one request-scoped caller with `query`, `mutation`, `action`, and `fetch` methods.
17
17
 
18
18
  ```ts [server/api/projects.get.ts]
19
19
  import { defineEventHandler } from 'nuxt/server'
@@ -61,6 +61,21 @@ options `queryTimeoutMs` and `maxResponseBytes`. They apply to every request;
61
61
  they are not per-call options. See
62
62
  [server limits](../../reference/module-configuration.md#server-limits).
63
63
 
64
+ ## Call an HTTP action
65
+
66
+ `fetch(path)` reads one of your Convex HTTP actions as the caller. It sends a
67
+ `GET` to `path` on the deployment's HTTP actions host, with the Convex session
68
+ token as `Authorization: Bearer`, and returns the upstream `Response`:
69
+
70
+ ```ts
71
+ const response = await serverConvex(event, { auth: 'required' }).fetch(`/files/${id}`)
72
+ ```
73
+
74
+ The body streams and is not capped at 1 MiB, so a file passes through your Nuxt
75
+ server. Use it for [private downloads](../files/private-downloads.md).
76
+ `fetch` accepts only a path and only `GET` or `HEAD`. It does not follow
77
+ redirects, so the token never reaches another host.
78
+
64
79
  ## Explicit credentials
65
80
 
66
81
  A trusted server workflow can pass a Convex JWT that it already has:
@@ -41,7 +41,7 @@ For a list with per-row actions, create an explicit per-row component:
41
41
 
42
42
  ```vue [app/components/ArchiveProjectButton.vue]
43
43
  <script setup lang="ts">
44
- import type { Id } from '~~/convex/_generated/dataModel'
44
+ import type { Id } from '#convex/dataModel'
45
45
  import { api } from '#convex/api'
46
46
 
47
47
  const props = defineProps<{ projectId: Id<'projects'> }>()
@@ -76,7 +76,7 @@ To edit an existing record, fill the form once from a query result. Then the for
76
76
  import { type } from 'arktype'
77
77
 
78
78
  import { api } from '#convex/api'
79
- import type { Id } from '~~/convex/_generated/dataModel'
79
+ import type { Id } from '#convex/dataModel'
80
80
 
81
81
  const props = defineProps<{ projectId: Id<'projects'> }>()
82
82
 
@@ -20,7 +20,7 @@ Some work needs several requests in a row: read a draft, upload a file, then pub
20
20
  ```vue [app/components/PublishDraft.vue]
21
21
  <script setup lang="ts">
22
22
  import { useConvexOperation } from '@lupinum/better-convex-nuxt/experimental'
23
- import type { Id } from '~~/convex/_generated/dataModel'
23
+ import type { Id } from '#convex/dataModel'
24
24
  import { api } from '#convex/api'
25
25
 
26
26
  const props = defineProps<{ draftId: Id<'drafts'> }>()
@@ -38,7 +38,7 @@ This example uses the `todos` table and functions from
38
38
  `api.todos.list` with `{}` as its arguments.
39
39
 
40
40
  ```ts
41
- import type { Id } from '~~/convex/_generated/dataModel'
41
+ import type { Id } from '#convex/dataModel'
42
42
  import { api } from '#convex/api'
43
43
 
44
44
  const { user } = useConvexAuth()
@@ -45,6 +45,8 @@ It works only with a development or local deployment, and it asks before each st
45
45
  4. It sets the secrets: `BETTER_AUTH_SECRETS` in Convex, and `BCN_AUTH_PROXY_IP_SECRET` in `.env.local` and in Convex. Nuxt signs each auth request with the proxy secret, and Convex checks the signature.
46
46
  5. It creates the first key that signs session tokens.
47
47
 
48
+ In a script or CI, `auth init --yes` accepts every step without asking.
49
+
48
50
  If step 5 fails, wait until the `pnpm dev` output shows `[convex] ✔ Convex functions ready!`, and run `pnpm exec better-convex-nuxt auth init` again. Running it again is safe.
49
51
 
50
52
  `auth init` wrote these files:
@@ -79,7 +81,7 @@ export const { ensureSigningKey, pruneSigningKeys, rotateSigningKey } = auth.jwk
79
81
  export const { onCreate, onUpdate, onDelete } = auth.triggerFunctions()
80
82
  ```
81
83
 
82
- No sign-in method is on until you name it. The file has no `email` hook yet, so codes are not mailed. On a local `SITE_URL`, they go to the Convex log (the dev outbox), which `pnpm dev` prints. Before you deploy, add the `email` hook; see [Transactional auth email](../build/authentication/transactional-email.md#add-the-email-hook).
84
+ No sign-in method is on until you name it. The file has no `email` hook yet, so codes are not mailed. On a local `SITE_URL`, they go to the Convex log (the dev outbox), which `pnpm dev` prints. Before you deploy, add the `email` hook. Locally, the codes still go to the log after you add it; see [Transactional auth email](../build/authentication/transactional-email.md#add-the-email-hook).
83
85
 
84
86
  The email in the session token is for display. Decide access from rows in Convex, not from this value. See [Session claims](../build/authentication/custom-user-fields.md#session-claims).
85
87
 
@@ -96,6 +98,10 @@ export default defineConvexAuthClient({
96
98
 
97
99
  ## Turn on auth in Nuxt
98
100
 
101
+ Stop `pnpm dev` with Ctrl-C. Nuxt reads `.env.local` only when it starts, and the new configuration needs `SITE_URL` from that file. If you change `nuxt.config.ts` while `pnpm dev` still runs, Nuxt reports `auth.origin is missing`.
102
+
103
+ Check that `.env.local` contains `SITE_URL`. `auth init` writes it, unless the Convex deployment already had a `SITE_URL`. In that case, add the same value to `.env.local`.
104
+
99
105
  Add the `convex` block to `nuxt.config.ts`. Keep your own `compatibilityDate`:
100
106
 
101
107
  ```ts [nuxt.config.ts]
@@ -119,7 +125,7 @@ export default defineNuxtConfig({
119
125
  - The `auth` object turns on auth. `origin` must be the exact public address of your Nuxt app.
120
126
  - `trustedClientIpHeader` may be empty only on `localhost`. On any other origin, Nuxt refuses to start without it. See [deployment](../operations/deployment.md).
121
127
 
122
- Stop `pnpm dev` with Ctrl-C and start it again, so Nuxt reads the new values in `.env.local`.
128
+ Start `pnpm dev` again.
123
129
 
124
130
  ## Move the todo list to `/todos`
125
131
 
@@ -242,7 +248,11 @@ async function sendCode() {
242
248
  async function signIn() {
243
249
  busy.value = true
244
250
  message.value = null
245
- const { error } = await client.signIn.emailOtp({ email: email.value, otp: code.value })
251
+ const { error } = await client.signIn.emailOtp({
252
+ email: email.value,
253
+ // A code copied from an email often has spaces around it.
254
+ otp: code.value.trim(),
255
+ })
246
256
  busy.value = false
247
257
  if (error) {
248
258
  message.value = explain(error)
@@ -24,6 +24,8 @@ import { ConvexError, v } from 'convex/values'
24
24
 
25
25
  import { mutation, query } from './_generated/server'
26
26
 
27
+ // Public on purpose in this step: anyone can call these functions.
28
+ // "Protect data" adds an owner to each todo and checks the user.
27
29
  export const list = query({
28
30
  args: {},
29
31
  handler: async (ctx) => {
@@ -40,6 +40,8 @@ import { ConvexError, v } from 'convex/values'
40
40
 
41
41
  import { mutation, query } from './_generated/server'
42
42
 
43
+ // Public on purpose in this step: anyone can call these functions.
44
+ // "Protect data" adds an owner to each todo and checks the user.
43
45
  export const list = query({
44
46
  args: {},
45
47
  handler: async (ctx) => {
@@ -64,7 +66,7 @@ export const create = mutation({
64
66
 
65
67
  When you save, Convex generates `api.todos.list` and `api.todos.create`, and the `pnpm dev` output shows `[convex] ✔ Convex functions ready!`.
66
68
 
67
- - A query reads data. `list` returns the 50 newest todos.
69
+ - A query reads data. `list` returns the 50 newest todos. Older todos stay in the database but do not show; [pagination](../build/queries/pagination.md) loads them page by page.
68
70
  - A mutation writes data. `create` checks the text, then inserts a todo.
69
71
 
70
72
  These functions are public on purpose: anyone can call them. [Protect data](./protect-data.md) adds an owner to each todo.
@@ -108,6 +108,9 @@ li {
108
108
  }
109
109
  li span {
110
110
  flex: 1;
111
+ min-width: 0;
112
+ /* A long word wraps instead of pushing Delete off-screen. */
113
+ overflow-wrap: anywhere;
111
114
  }
112
115
  .done {
113
116
  text-decoration: line-through;
@@ -35,6 +35,36 @@ With operations from `@lupinum/better-convex-functions`, use
35
35
  [the MCP door](../build/agents/mcp-door.md) instead of registering tools by
36
36
  hand.
37
37
 
38
+ ## Type-check and build
39
+
40
+ `pnpm dev` loads `.env.local`. `nuxt build` does not, so pass the file to it.
41
+ Add these scripts, as in `starters/tutorial`:
42
+
43
+ ```json [package.json]
44
+ {
45
+ "scripts": {
46
+ "build": "nuxt build --dotenv .env.local",
47
+ "typecheck": "nuxt typecheck --dotenv .env.local && tsc -p convex --noEmit"
48
+ }
49
+ }
50
+ ```
51
+
52
+ `nuxt typecheck` needs `vue-tsc`, and `nuxt.config.ts` needs the Node types
53
+ for `process.env`:
54
+
55
+ ```bash
56
+ pnpm add -D vue-tsc typescript@~5.9.3 @types/node
57
+ ```
58
+
59
+ Keep TypeScript at 5.9: `vue-tsc` 3 does not run on TypeScript 7.
60
+
61
+ On your computer, `pnpm build` warns about the loopback auth origin
62
+ `http://localhost:3000`. The warning is correct for a local build: it uses the
63
+ `SITE_URL` from `.env.local`.
64
+
65
+ On your host and in CI there is no `.env.local`. Set `SITE_URL` and the other
66
+ [environment variables](../operations/environment-variables.md) there instead.
67
+
38
68
  ## Deploy
39
69
 
40
70
  Before the first deploy of the tutorial app, add the `email` hook to `convex/auth.ts`, so codes are mailed instead of logged: [Transactional auth email](../build/authentication/transactional-email.md#add-the-email-hook).
@@ -22,11 +22,32 @@ server rendering, Nuxt server routes, or the built-in Better Auth setup.
22
22
 
23
23
  ## Install
24
24
 
25
+ Create a Vite app with Vue and TypeScript, or skip this step in an existing app:
26
+
27
+ ```bash
28
+ pnpm create vite@latest my-vue-app --template vue-ts
29
+ cd my-vue-app
30
+ pnpm install
31
+ ```
32
+
33
+ Add the package and Convex:
34
+
25
35
  ```bash
26
36
  pnpm add @lupinum/better-convex-vue convex@^1.42.2 vue@^3.5.0
27
37
  ```
28
38
 
29
- The package needs `vue` `>=3.5.0 <4` and `convex` `>=1.42.2 <2`.
39
+ The package needs `vue` `>=3.5.0 <4` and `convex` `>=1.42.2 <2`. When pnpm
40
+ reports that it ignored the build script of `esbuild`, run `pnpm approve-builds`
41
+ and allow it.
42
+
43
+ ## Start Convex
44
+
45
+ Run `npx convex dev` in the project folder and keep it running. On the first
46
+ run it asks you to log in or to start without an account; without an account,
47
+ Convex runs on your computer. It creates the `convex/` folder, writes
48
+ `VITE_CONVEX_URL` to `.env.local`, and keeps `convex/_generated/api` up to date
49
+ while it runs. A cloud deployment URL ends in `.convex.cloud`; a local one is
50
+ `http://127.0.0.1:3210`.
30
51
 
31
52
  ## Anonymous application
32
53
 
@@ -49,13 +70,6 @@ app.use(
49
70
  app.mount('#app')
50
71
  ```
51
72
 
52
- Set `VITE_CONVEX_URL` in `.env.local` to your deployment URL. It ends in
53
- `.convex.cloud`. The Convex dashboard shows it in the deployment settings.
54
-
55
- Run `npx convex dev` in the project folder. It connects a deployment, writes
56
- `VITE_CONVEX_URL` to `.env.local`, creates the `convex/` folder, and keeps
57
- `convex/_generated/api` up to date while it runs.
58
-
59
73
  Add the Convex functions that the component below uses:
60
74
 
61
75
  ```ts [convex/schema.ts]
@@ -68,49 +82,34 @@ export default defineSchema({
68
82
  ```
69
83
 
70
84
  ```ts [convex/notes.ts]
71
- import { v } from 'convex/values'
85
+ import { ConvexError, v } from 'convex/values'
72
86
 
73
87
  import { mutation, query } from './_generated/server'
74
88
 
89
+ // Public on purpose: this anonymous example lets anyone read and rename notes.
90
+ // A real application checks the user and their permission in each function.
75
91
  export const list = query({
76
92
  args: {},
77
93
  handler: (ctx) => ctx.db.query('notes').order('desc').take(50),
78
94
  })
79
95
 
80
- // This anonymous example lets anyone rename a note. A real application checks
81
- // the user and their permission in the mutation.
82
96
  export const rename = mutation({
83
97
  args: { id: v.id('notes'), title: v.string() },
84
98
  handler: async (ctx, { id, title }) => {
85
- await ctx.db.patch(id, { title: title.trim().slice(0, 200) })
99
+ const trimmed = title.trim().slice(0, 200)
100
+ if (!trimmed) throw new ConvexError({ code: 'EMPTY_TITLE', message: 'Title is empty' })
101
+ await ctx.db.patch(id, { title: trimmed })
86
102
  },
87
103
  })
88
104
  ```
89
105
 
90
- Add a note in the Convex dashboard (Data → `notes` → Add) so the list is not
91
- empty.
106
+ Open the dashboard with `npx convex dashboard` and add a note (Data → `notes`
107
+ → Add), so the list is not empty.
92
108
 
93
- When your application has sign-in, store the owner on each note and check it in
94
- the mutation. `ctx.auth.getUserIdentity()` works with every auth provider. It does not check that the session is still valid. With the Nuxt module's auth, use `auth.requireUser(ctx)` instead (see [Protect data](./protect-data.md)):
95
-
96
- ```ts [convex/notes.ts]
97
- import { ConvexError, v } from 'convex/values'
98
-
99
- import { mutation } from './_generated/server'
100
-
101
- // Needs `ownerId: v.string()` on the `notes` table.
102
- export const renameOwn = mutation({
103
- args: { id: v.id('notes'), title: v.string() },
104
- handler: async (ctx, { id, title }) => {
105
- const identity = await ctx.auth.getUserIdentity()
106
- const note = await ctx.db.get(id)
107
- if (!identity || !note || note.ownerId !== identity.subject) {
108
- throw new ConvexError({ code: 'NOTE_NOT_FOUND' })
109
- }
110
- await ctx.db.patch(id, { title: title.trim().slice(0, 200) })
111
- },
112
- })
113
- ```
109
+ When your application has sign-in, do not keep these public functions. Replace
110
+ them with the functions under
111
+ [Authentication with any provider](#authentication-with-any-provider), which
112
+ check the user.
114
113
 
115
114
  Then use the composables in components. They return refs right away. You do not
116
115
  await them:
@@ -149,7 +148,8 @@ import Notes from './components/Notes.vue'
149
148
  </template>
150
149
  ```
151
150
 
152
- Open the app in two tabs and rename a note in one. The other tab updates
151
+ Start the app in a second terminal with `pnpm dev`, and open the address that
152
+ Vite prints. Open it in two tabs and rename a note in one. The other tab updates
153
153
  without a reload.
154
154
 
155
155
  A query with `args: {}` may omit the arguments. Every other query needs an
@@ -164,12 +164,37 @@ successful data, not a loading or skip sentinel.
164
164
  A page that loads its data after it appears flashes empty and then moves its
165
165
  content. To show the page only when its data exists, await its queries and
166
166
  render it inside Vue's `<Suspense>`. A component that awaits does not render
167
- at all without a `<Suspense>` above it:
167
+ at all without a `<Suspense>` above it.
168
+
169
+ This section uses Vue Router. Install it:
170
+
171
+ ```bash
172
+ pnpm add vue-router
173
+ ```
174
+
175
+ Create the router with the notes page:
176
+
177
+ ```ts [src/router.ts]
178
+ import { createRouter, createWebHistory } from 'vue-router'
179
+
180
+ import NotesPage from './pages/NotesPage.vue'
181
+
182
+ export const router = createRouter({
183
+ history: createWebHistory(),
184
+ routes: [{ path: '/', component: NotesPage }],
185
+ })
186
+ ```
187
+
188
+ Install it in `src/main.ts`: import `router` from `./router` and add
189
+ `app.use(router)` before `app.mount('#app')`. Then replace `src/App.vue`, so
190
+ each page renders inside `<Suspense>`. The `v-if` keeps `<Suspense>` out until
191
+ the router has its first page. Without it, Vue logs a warning on every page
192
+ load.
168
193
 
169
194
  ```vue [src/App.vue]
170
195
  <template>
171
196
  <RouterView v-slot="{ Component }">
172
- <Suspense>
197
+ <Suspense v-if="Component">
173
198
  <component :is="Component" />
174
199
  </Suspense>
175
200
  </RouterView>
@@ -183,6 +208,13 @@ import { useConvexQuery } from '@lupinum/better-convex-vue'
183
208
 
184
209
  const { data: notes, error } = await useConvexQuery(api.notes.list, {})
185
210
  </script>
211
+
212
+ <template>
213
+ <p v-if="error">Could not load notes.</p>
214
+ <ul v-else>
215
+ <li v-for="note in notes" :key="note._id">{{ note.title }}</li>
216
+ </ul>
217
+ </template>
186
218
  ```
187
219
 
188
220
  When the route shows a different page component, `<Suspense>` keeps the
@@ -208,18 +240,25 @@ Vue marks `<Suspense>` as experimental.
208
240
 
209
241
  `<Suspense>` waits after the router changed the URL, and child components load
210
242
  only after their parent. To load a page's data before the navigation finishes,
211
- preload it in a router guard. This needs Vue Router 4.2 or later:
243
+ preload it in a router guard. This needs Vue Router 4.2 or later. In this
244
+ example, `ProjectPage.vue`, `api.projects.get`, and `api.tasks.list` stand for
245
+ your own page and its queries:
212
246
 
213
247
  ```ts [src/router.ts]
214
248
  import { preloadConvexQuery } from '@lupinum/better-convex-vue'
215
249
  import { createRouter, createWebHistory } from 'vue-router'
250
+
216
251
  import { api } from '../convex/_generated/api'
217
252
  import type { Id } from '../convex/_generated/dataModel'
253
+ import NotesPage from './pages/NotesPage.vue'
218
254
  import ProjectPage from './pages/ProjectPage.vue'
219
255
 
220
256
  export const router = createRouter({
221
257
  history: createWebHistory(),
222
- routes: [{ path: '/projects/:id', name: 'project', component: ProjectPage }],
258
+ routes: [
259
+ { path: '/', component: NotesPage },
260
+ { path: '/projects/:id', name: 'project', component: ProjectPage },
261
+ ],
223
262
  })
224
263
 
225
264
  router.beforeResolve(async (to) => {
@@ -356,9 +395,12 @@ export const auth: BetterConvexAuthAdapter = {
356
395
  gives `fetchToken` time to wait out a failure while the current token still
357
396
  works. Keep it well below the token lifetime.
358
397
 
359
- Install the adapter with the plugin:
398
+ Install the adapter in `src/main.ts`: import `auth` from `./convex-auth` and
399
+ pass it to the plugin. Keep the rest of the file:
360
400
 
361
401
  ```ts [src/main.ts]
402
+ import { auth } from './convex-auth'
403
+
362
404
  app.use(
363
405
  createBetterConvex({
364
406
  convexUrl: import.meta.env.VITE_CONVEX_URL,
@@ -371,6 +413,66 @@ Your backend issues the Convex token. Never put provider secrets, cookies,
371
413
  refresh tokens, deployment keys, or signing keys in the Vite bundle. Check
372
414
  permissions in every protected Convex function.
373
415
 
416
+ With sign-in, no function of the notes example stays public. Store the owner on
417
+ each note. Convex rejects the new schema while a note without an owner exists,
418
+ so delete those notes in the dashboard first:
419
+
420
+ ```ts [convex/schema.ts]
421
+ import { defineSchema, defineTable } from 'convex/server'
422
+ import { v } from 'convex/values'
423
+
424
+ export default defineSchema({
425
+ notes: defineTable({ ownerId: v.string(), title: v.string() }).index('by_owner', ['ownerId']),
426
+ })
427
+ ```
428
+
429
+ Replace `convex/notes.ts`. Each function reads the user from the Convex token
430
+ and uses only the notes of that user:
431
+
432
+ ```ts [convex/notes.ts]
433
+ import { ConvexError, v } from 'convex/values'
434
+
435
+ import { mutation, query } from './_generated/server'
436
+
437
+ export const list = query({
438
+ args: {},
439
+ handler: async (ctx) => {
440
+ const identity = await ctx.auth.getUserIdentity()
441
+ if (!identity) {
442
+ throw new ConvexError({ code: 'UNAUTHENTICATED', message: 'Authentication required' })
443
+ }
444
+ return await ctx.db
445
+ .query('notes')
446
+ .withIndex('by_owner', (q) => q.eq('ownerId', identity.subject))
447
+ .order('desc')
448
+ .take(50)
449
+ },
450
+ })
451
+
452
+ export const rename = mutation({
453
+ args: { id: v.id('notes'), title: v.string() },
454
+ handler: async (ctx, { id, title }) => {
455
+ const identity = await ctx.auth.getUserIdentity()
456
+ const note = await ctx.db.get(id)
457
+ // The same error for a missing note and for a note of another user.
458
+ if (!identity || !note || note.ownerId !== identity.subject) {
459
+ throw new ConvexError({ code: 'NOTE_NOT_FOUND', message: 'Note not found' })
460
+ }
461
+ const trimmed = title.trim().slice(0, 200)
462
+ if (!trimmed) throw new ConvexError({ code: 'EMPTY_TITLE', message: 'Title is empty' })
463
+ await ctx.db.patch(id, { title: trimmed })
464
+ },
465
+ })
466
+ ```
467
+
468
+ - `ctx.auth.getUserIdentity()` works with every auth provider. It does not check
469
+ that the session is still valid. With the Nuxt module's auth, use
470
+ `auth.requireUser(ctx)` instead (see [Protect data](./protect-data.md)).
471
+ - A mutation that creates a note sets `ownerId` from `identity.subject`, never
472
+ from an argument.
473
+ - In `Notes.vue`, pass `{ auth: 'required' }` as the third argument of
474
+ `useConvexQuery`. The query then does not run while nobody is signed in.
475
+
374
476
  ## Embedded Vue applications
375
477
 
376
478
  A Nuxt app can share its Convex connection with a separately built Vue app that
@@ -65,6 +65,6 @@ test('the app has no launch problems', async () => {
65
65
  | Data region | Choose the region when you create the deployment (EU for EU users); it cannot be changed later | Personal data sits in the wrong region, and moving it means export and import. |
66
66
  | Backups | Convex backups, and test one restore | An untested backup can fail on the day you need it. |
67
67
  | Separate dev and production | Separate deployments and secrets | Test data and test keys reach production. |
68
- | Monitoring | Convex log streams | You learn about errors from your users. |
68
+ | Monitoring | Convex log streams with [call events](./log-streams.md) | You learn about errors from your users. |
69
69
 
70
70
  This page is a checklist. It does not make an app compliant with any law on its own.