nuxt-backend 0.1.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 (106) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +744 -0
  3. package/dist/convex/auth.config.d.ts +9 -0
  4. package/dist/convex/auth.config.d.ts.map +1 -0
  5. package/dist/convex/auth.config.js +14 -0
  6. package/dist/convex/auth.config.js.map +1 -0
  7. package/dist/convex/client/index.d.ts +12784 -0
  8. package/dist/convex/client/index.d.ts.map +1 -0
  9. package/dist/convex/client/index.js +230 -0
  10. package/dist/convex/client/index.js.map +1 -0
  11. package/dist/convex/component/_generated/api.d.ts +36 -0
  12. package/dist/convex/component/_generated/api.d.ts.map +1 -0
  13. package/dist/convex/component/_generated/api.js +31 -0
  14. package/dist/convex/component/_generated/api.js.map +1 -0
  15. package/dist/convex/component/_generated/component.d.ts +549 -0
  16. package/dist/convex/component/_generated/component.d.ts.map +1 -0
  17. package/dist/convex/component/_generated/component.js +11 -0
  18. package/dist/convex/component/_generated/component.js.map +1 -0
  19. package/dist/convex/component/_generated/dataModel.d.ts +46 -0
  20. package/dist/convex/component/_generated/dataModel.d.ts.map +1 -0
  21. package/dist/convex/component/_generated/dataModel.js +11 -0
  22. package/dist/convex/component/_generated/dataModel.js.map +1 -0
  23. package/dist/convex/component/_generated/server.d.ts +121 -0
  24. package/dist/convex/component/_generated/server.d.ts.map +1 -0
  25. package/dist/convex/component/_generated/server.js +78 -0
  26. package/dist/convex/component/_generated/server.js.map +1 -0
  27. package/dist/convex/component/adapter.d.ts +3 -0
  28. package/dist/convex/component/adapter.d.ts.map +1 -0
  29. package/dist/convex/component/adapter.js +23 -0
  30. package/dist/convex/component/adapter.js.map +1 -0
  31. package/dist/convex/component/constants.d.ts +3 -0
  32. package/dist/convex/component/constants.d.ts.map +1 -0
  33. package/dist/convex/component/constants.js +3 -0
  34. package/dist/convex/component/constants.js.map +1 -0
  35. package/dist/convex/component/convex.config.d.ts +14 -0
  36. package/dist/convex/component/convex.config.d.ts.map +1 -0
  37. package/dist/convex/component/convex.config.js +15 -0
  38. package/dist/convex/component/convex.config.js.map +1 -0
  39. package/dist/convex/component/schema.d.ts +278 -0
  40. package/dist/convex/component/schema.d.ts.map +1 -0
  41. package/dist/convex/component/schema.js +91 -0
  42. package/dist/convex/component/schema.js.map +1 -0
  43. package/dist/module.d.ts +47 -0
  44. package/dist/module.js +275 -0
  45. package/dist/module.json +9 -0
  46. package/dist/runtime/nuxt/auth/middleware.d.ts +12 -0
  47. package/dist/runtime/nuxt/auth/middleware.js +31 -0
  48. package/dist/runtime/nuxt/auth/proxy.d.ts +6 -0
  49. package/dist/runtime/nuxt/auth/proxy.js +11 -0
  50. package/dist/runtime/nuxt/auth/server.d.ts +86 -0
  51. package/dist/runtime/nuxt/auth/server.js +110 -0
  52. package/dist/runtime/nuxt/config.d.ts +7 -0
  53. package/dist/runtime/nuxt/config.js +12 -0
  54. package/dist/runtime/nuxt/index.d.ts +102 -0
  55. package/dist/runtime/nuxt/index.js +77 -0
  56. package/dist/runtime/vue/auth/client.d.ts +14 -0
  57. package/dist/runtime/vue/auth/client.js +7 -0
  58. package/dist/runtime/vue/auth/cross-domain.d.ts +8 -0
  59. package/dist/runtime/vue/auth/cross-domain.js +34 -0
  60. package/dist/runtime/vue/auth/helpers.d.ts +52 -0
  61. package/dist/runtime/vue/auth/helpers.js +35 -0
  62. package/dist/runtime/vue/auth/hydration.d.ts +14 -0
  63. package/dist/runtime/vue/auth/hydration.js +23 -0
  64. package/dist/runtime/vue/auth/index.d.ts +79 -0
  65. package/dist/runtime/vue/auth/index.js +81 -0
  66. package/dist/runtime/vue/auth/plugin.client.d.ts +6 -0
  67. package/dist/runtime/vue/auth/plugin.client.js +30 -0
  68. package/dist/runtime/vue/auth/plugin.server.d.ts +17 -0
  69. package/dist/runtime/vue/auth/plugin.server.js +29 -0
  70. package/dist/runtime/vue/auth/use-auth.d.ts +84 -0
  71. package/dist/runtime/vue/auth/use-auth.js +77 -0
  72. package/dist/runtime/vue/client.d.ts +245 -0
  73. package/dist/runtime/vue/client.js +341 -0
  74. package/dist/runtime/vue/composables/use-action.d.ts +45 -0
  75. package/dist/runtime/vue/composables/use-action.js +10 -0
  76. package/dist/runtime/vue/composables/use-connection-state.d.ts +25 -0
  77. package/dist/runtime/vue/composables/use-connection-state.js +13 -0
  78. package/dist/runtime/vue/composables/use-mutation.d.ts +60 -0
  79. package/dist/runtime/vue/composables/use-mutation.js +36 -0
  80. package/dist/runtime/vue/composables/use-paginated-query.d.ts +101 -0
  81. package/dist/runtime/vue/composables/use-paginated-query.js +508 -0
  82. package/dist/runtime/vue/composables/use-queries.d.ts +45 -0
  83. package/dist/runtime/vue/composables/use-queries.js +32 -0
  84. package/dist/runtime/vue/composables/use-query.d.ts +82 -0
  85. package/dist/runtime/vue/composables/use-query.js +63 -0
  86. package/dist/runtime/vue/composables/use-subscription.d.ts +14 -0
  87. package/dist/runtime/vue/composables/use-subscription.js +15 -0
  88. package/dist/runtime/vue/hydration.d.ts +42 -0
  89. package/dist/runtime/vue/hydration.js +18 -0
  90. package/dist/runtime/vue/index.d.ts +29 -0
  91. package/dist/runtime/vue/index.js +38 -0
  92. package/dist/runtime/vue/queries-observer.d.ts +38 -0
  93. package/dist/runtime/vue/queries-observer.js +127 -0
  94. package/dist/types.d.ts +3 -0
  95. package/package.json +157 -0
  96. package/src/convex/auth.config.ts +21 -0
  97. package/src/convex/client/index.ts +329 -0
  98. package/src/convex/component/_generated/api.ts +52 -0
  99. package/src/convex/component/_generated/component.ts +1338 -0
  100. package/src/convex/component/_generated/dataModel.ts +60 -0
  101. package/src/convex/component/_generated/server.ts +156 -0
  102. package/src/convex/component/adapter.ts +42 -0
  103. package/src/convex/component/constants.ts +2 -0
  104. package/src/convex/component/convex.config.ts +16 -0
  105. package/src/convex/component/schema.ts +93 -0
  106. package/src/convex/test.ts +34 -0
package/README.md ADDED
@@ -0,0 +1,744 @@
1
+ # nuxt-backend
2
+
3
+ [![npm version][npm-version-src]][npm-version-href]
4
+ [![npm downloads][npm-downloads-src]][npm-downloads-href]
5
+ [![License][license-src]][license-href]
6
+ [![Nuxt][nuxt-src]][nuxt-href]
7
+
8
+ Integrate [Convex](https://convex.dev) with [Nuxt](https://nuxt.com) — one package that ships a **Nuxt module** and a **Convex auth component** with [Better Auth](https://www.better-auth.com) built in.
9
+
10
+ `nuxt-backend` is a Vue/Nuxt port of the official Convex + Better Auth React/Next integration. It keeps the same core pieces — the Better Auth Convex plugin, Convex auth config, server helpers, auth-aware preloading, and client auth state — but preconfigures the route wiring and component setup so new Nuxt apps do less manual installation work.
11
+
12
+ > This README covers setup and the end-to-end integration flow. Full API details, exports, architecture, and development notes are in [docs/reference.md](./docs/reference.md).
13
+
14
+ ## What this module provides
15
+
16
+ Adding `modules: ['nuxt-backend']` registers the following surface, described in standard Nuxt module terms. Grouped by where each piece lives. Full signatures, argument types, and the import tree are in the [API reference](#api-reference) below.
17
+
18
+ ### ⚙️ Configuration
19
+
20
+ - **Module options** (`backend` config key) — `url`, `siteUrl`, `authRoute`, `installation`. All optional; URLs fall back to env vars.
21
+ - **Runtime config** — `runtimeConfig.public.backend.{url,siteUrl}` and `runtimeConfig.backend.siteUrl`, resolved from module options or `NUXT_PUBLIC_CONVEX_URL` / `NUXT_PUBLIC_CONVEX_SITE_URL`.
22
+
23
+ ### 🖼️ App runtime (Vue)
24
+
25
+ - **Nuxt plugins** — a client Convex plugin and an SSR auth-token prefetch plugin; injects `useNuxtApp().$convex`.
26
+ - **Auto-imported composables** — `useConvex`, `useQuery` (+ `useConvexQuery`, `useQuery_experimental`), `useQueries` (+ `useConvexQueries`), `useMutation` (+ `useConvexMutation`), `useAction` (+ `useConvexAction`), `usePaginatedQuery` (+ `usePaginatedQuery_experimental`), `usePreloadedQuery`, `usePreloadedAuthQuery`, `useConvexConnectionState`, `useConvexAuth`, `provideConvexAuth`, and `useAuth`.
27
+ - **Auto-registered components** — `<Authenticated>`, `<Unauthenticated>`, `<AuthLoading>`.
28
+ - **Route middleware** — `auth`, opt-in per page via `definePageMeta({ middleware: 'auth' })` (registered non-global, so installing the module never guards routes by surprise).
29
+
30
+ ### 🛠️ Server (Nitro)
31
+
32
+ - **Server route** — `${backend.authRoute}/**` (default `/api/auth/**`): a same-origin Better Auth proxy that keeps cookies on your domain.
33
+ - **Server auto-imports** — `fetchQuery`, `fetchMutation`, `fetchAction`, `preloadQuery`, `preloadedQueryResult`, `backendAuth` (available in `server/` routes, Nitro handlers, and middleware).
34
+
35
+ ### 🧩 Project wiring & types
36
+
37
+ - **Import aliases** — `#backend`, `#backend/api`, `#backend/server`, `#backend/dataModel`, and `#backend/_generated`, registered for both Vite and Nitro, pointing at your Convex functions directory and its [generated files](https://docs.convex.dev/generated-api/).
38
+ - **Scaffolded files** (first run) — `backend/convex.config.ts`, `auth.config.ts`, `auth.ts`, `http.ts`; local mode also creates `backend/components/backend/*`.
39
+ - **Type augmentation** — runtime config keys, the injected `$convex`, auto-imported composables, auto-registered components, and package subpath declarations all become typed after Nuxt preparation.
40
+
41
+ ### 🔐 Convex auth bridge (package entrypoints)
42
+
43
+ - **Better Auth component** — email/password auth out of the box, a Convex adapter for persistence, and HTTP auth endpoints served through Convex.
44
+ - **Entrypoints** — `nuxt-backend` (the module), `nuxt-backend/convex` (`setupAuth`, `createAuth`, `createAuthOptions`, `makeAuthApi`, `createBetterAuth`), `nuxt-backend/convex/component/convex.config`, `nuxt-backend/convex/component/schema`, `nuxt-backend/convex/auth.config`, and `nuxt-backend/convex/test`. (`getAuthUser`, `authComponent`, and `options` are returned by `setupAuth(...)`, not direct exports.)
45
+
46
+ ### Full Nuxt module surface
47
+
48
+ `nuxt-backend` deliberately uses only the part of the Nuxt module API that an auth/data integration needs, and leaves routing, layout, and styling to your app. The table below triages the complete set of things a Nuxt module *can* provide against what this module does.
49
+
50
+ <details>
51
+ <summary>Provided vs. intentionally app-owned</summary>
52
+
53
+ | Capability (Nuxt Kit / mechanism) | In `nuxt-backend` |
54
+ |---|---|
55
+ | Module options · `defineNuxtModule({ configKey })` | ✅ `backend.url`, `siteUrl`, `authRoute`, `installation` |
56
+ | Runtime config · `options.runtimeConfig` / `updateRuntimeConfig` | ✅ public + private `backend` keys |
57
+ | App plugins · `addPlugin` / `addPluginTemplate` | ✅ client + server plugins, injects `$convex` |
58
+ | Auto-imported composables · `addImports` / `addImportsDir` | ✅ Convex + auth composables |
59
+ | Auto-imported components · `addComponent` / `addComponentsDir` | ✅ `<Authenticated>`, `<Unauthenticated>`, `<AuthLoading>` |
60
+ | Route middleware · `addRouteMiddleware` | ✅ `auth` (opt-in, non-global) |
61
+ | Server routes / middleware · `addServerHandler` | ✅ auth proxy at `authRoute/**` |
62
+ | Server auto-imports · `addServerImports` / `addServerImportsDir` | ✅ `fetchQuery`, `preloadQuery`, `backendAuth`, … |
63
+ | Import aliases · `options.alias` (+ `nitro.alias`) | ✅ `#backend`, `#backend/api`, `#backend/server`, `#backend/dataModel`, `#backend/_generated` |
64
+ | Type augmentation · `declare module` / `addTypeTemplate` | ✅ runtime config + generated declarations |
65
+ | Package entrypoints · `exports` map | ✅ 6 subpaths (module + Convex bridge) |
66
+ | Scaffolded files on disk | ✅ first-run Convex wiring (module-specific) |
67
+ | Layouts · `addLayout` | — app-owned |
68
+ | Pages / routes · `extendPages` | — app-owned |
69
+ | Route rules · `extendRouteRules` | — app-owned |
70
+ | Global head · `setGlobalHead` / `app.head` | — app-owned |
71
+ | Global CSS · `options.css` | — app-owned |
72
+ | Global route middleware · `addRouteMiddleware({ global: true })` | — app-owned (auth is opt-in) |
73
+ | App config · `options.appConfig` | — not used |
74
+ | Nitro plugins · `addServerPlugin` | — not used |
75
+ | Server scan dirs / virtual files · `addServerScanDir` / `addServerTemplate` | — not used |
76
+ | Dev-only handlers · `addDevServerHandler` | — not used |
77
+ | Prerender routes · `addPrerenderRoutes` | — app-owned |
78
+ | Virtual files · `addTemplate` / `updateTemplates` | — not used (physical scaffold instead) |
79
+ | Bundler plugins / config · `addVitePlugin` / `extendViteConfig` / `build.transpile` | — not used |
80
+ | Module dependencies · `moduleDependencies` / `installModule` | — not used |
81
+ | Compatibility constraints · `meta.compatibility` | — not declared |
82
+ | Nuxt layer · `extends` | — not shipped as a layer |
83
+
84
+ </details>
85
+
86
+ Keeping pages, layouts, global CSS, global middleware, route rules, and layers app-owned means installing the module never changes your routing, layout, styling, or domain behavior.
87
+
88
+ ## Installation
89
+
90
+ ### 1. Install the package
91
+
92
+ ```bash
93
+ npx nuxi@latest module add nuxt-backend
94
+ ```
95
+
96
+ <details>
97
+
98
+ <summary>…or install using your dependency manager</summary>
99
+
100
+ ```bash
101
+ # Using pnpm
102
+ pnpm add nuxt-backend
103
+
104
+ # Using yarn
105
+ yarn add nuxt-backend
106
+
107
+ # Using npm
108
+ npm install nuxt-backend
109
+ ```
110
+
111
+ </details>
112
+
113
+ ### 2. Add the Nuxt module
114
+
115
+ ```ts
116
+ // nuxt.config.ts
117
+ export default defineNuxtConfig({
118
+ modules: ['nuxt-backend'],
119
+ })
120
+ ```
121
+
122
+ ### 3. Configure environment variables
123
+
124
+ Create a `.env.local` file in the app root:
125
+
126
+ ```bash
127
+ # .env.local
128
+ NUXT_PUBLIC_CONVEX_URL=https://your-deployment.convex.cloud
129
+ NUXT_PUBLIC_CONVEX_SITE_URL=https://your-deployment.convex.site
130
+ ```
131
+
132
+ These are the only app environment variables auto-detected by the module.
133
+
134
+ Set the Convex deployment environment variables via the CLI:
135
+
136
+ ```bash
137
+ npx convex env set BETTER_AUTH_SECRET=$(openssl rand -base64 32)
138
+ npx convex env set SITE_URL https://nuxt-backend.localhost
139
+ ```
140
+
141
+ Or set them manually in the [Convex dashboard](https://dashboard.convex.dev). These variables are added to the `.env.local` file created by `npx convex dev` and will be picked up by your framework dev server.
142
+
143
+ So the required values are split like this:
144
+
145
+ - `.env.local` in the Nuxt app: `NUXT_PUBLIC_CONVEX_URL`, `NUXT_PUBLIC_CONVEX_SITE_URL`
146
+ - Convex dashboard env vars: `SITE_URL`, `BETTER_AUTH_SECRET`
147
+
148
+ ### 4. Optional: override module defaults
149
+
150
+ Most apps do not need a `backend` block in `nuxt.config.ts`. Add it only if you want to override the env-based defaults or change the auth route:
151
+
152
+ ```ts
153
+ // nuxt.config.ts
154
+ export default defineNuxtConfig({
155
+ modules: ['nuxt-backend'],
156
+ backend: {
157
+ url: 'https://your-deployment.convex.cloud',
158
+ siteUrl: 'https://your-deployment.convex.site',
159
+ authRoute: '/api/auth',
160
+ },
161
+ })
162
+ ```
163
+
164
+ ### 5. Start the app once so the backend files are scaffolded
165
+
166
+ ```bash
167
+ npm run dev
168
+ ```
169
+
170
+ On first run, the module creates the minimum Convex files needed to mount the packaged Better Auth component and register the official auth routes. This replaces the manual `convex/betterAuth/*` component setup from the official guide with a prebuilt component and root helpers. If the app already has a Convex functions directory, scaffolding reuses it. Otherwise it creates `backend/` by default:
171
+
172
+ ```text
173
+ your-project/
174
+ ├── backend/
175
+ │ ├── convex.config.ts
176
+ │ ├── auth.config.ts
177
+ │ ├── auth.ts
178
+ │ └── http.ts
179
+ └── convex.json
180
+ ```
181
+
182
+ `convex.json` is only generated when the functions directory is non-standard (anything other than `convex/`).
183
+
184
+ ### 6. Start Convex
185
+
186
+ ```bash
187
+ npx convex dev
188
+ ```
189
+
190
+ Deploy with:
191
+
192
+ ```bash
193
+ npx convex deploy
194
+ ```
195
+
196
+ ## Usage
197
+
198
+ The intended integration shape is:
199
+
200
+ - Nuxt owns the UI, route middleware, SSR handlers, and the same-origin auth proxy.
201
+ - Convex owns data, real-time subscriptions, Better Auth persistence, and auth identity.
202
+ - `nuxt-backend` keeps the auth route, auth config, and client/server helpers aligned.
203
+
204
+ A complete working example lives in [`playground/`](./playground) — sign-in/sign-up page, protected todos page with auth-aware SSR preload, Convex queries/mutations, and `auth` middleware.
205
+
206
+ ### 1. Keep the scaffolded Convex files aligned
207
+
208
+ If you let the module scaffold files, you can keep them as generated. If you create them manually, they should look like this:
209
+
210
+ ```ts
211
+ // backend/convex.config.ts
212
+ import { defineApp } from 'convex/server'
213
+ import backend from 'nuxt-backend/convex/component/convex.config'
214
+
215
+ const app = defineApp()
216
+ app.use(backend)
217
+ export default app
218
+ ```
219
+
220
+ ```ts
221
+ // backend/auth.config.ts
222
+ export { default } from 'nuxt-backend/convex/auth.config'
223
+ ```
224
+
225
+ ```ts
226
+ // backend/auth.ts
227
+ import { setupAuth } from 'nuxt-backend/convex'
228
+ import { components } from './_generated/api'
229
+ import { query } from './_generated/server'
230
+
231
+ export const {
232
+ authComponent,
233
+ createAuthOptions,
234
+ options,
235
+ createAuth,
236
+ getAuthUser,
237
+ } = setupAuth(components.backend, query)
238
+ ```
239
+
240
+ ```ts
241
+ // backend/http.ts
242
+ import { httpRouter } from 'convex/server'
243
+ import { authComponent, createAuth } from './auth'
244
+
245
+ const http = httpRouter()
246
+ authComponent.registerRoutes(http, createAuth)
247
+
248
+ export default http
249
+ ```
250
+
251
+ That setup mounts the packaged Better Auth component, configures Convex to trust its tokens, and exposes `api.auth.getAuthUser` for app queries.
252
+
253
+ ### Local hybrid install
254
+
255
+ Auth is always installed. Use local installation mode when you want to own the Better Auth schema, add custom indexes, or regenerate schema after adding Better Auth plugins:
256
+
257
+ ```ts
258
+ // nuxt.config.ts
259
+ export default defineNuxtConfig({
260
+ modules: ['nuxt-backend'],
261
+ backend: {
262
+ installation: 'local',
263
+ },
264
+ })
265
+ ```
266
+
267
+ The first run scaffolds `backend/components/backend/*` with a local `convex.config.ts`, `schema.ts`, `adapter.ts`, and a schema-generation `auth.ts`. The app-facing `backend/auth.ts` still exports `authComponent`, `createAuthOptions`, `options`, and `createAuth`, matching the official Better Auth Convex API while hiding the installation details behind the Nuxt module.
268
+
269
+ After changing Better Auth plugins or schema-affecting options, regenerate the local schema and keep your custom indexes in `schema.ts`:
270
+
271
+ ```bash
272
+ npx auth generate --config ./backend/components/backend/auth.ts --output ./backend/components/backend/generated-schema.ts
273
+ ```
274
+
275
+ ### 2. Sign in from Nuxt
276
+
277
+ ```vue
278
+ <!-- pages/login.vue -->
279
+ <script setup lang="ts">
280
+ const { client: auth } = useAuth()
281
+ const email = ref('')
282
+ const password = ref('')
283
+ const pending = ref(false)
284
+ const error = ref<string | null>(null)
285
+
286
+ async function signIn() {
287
+ pending.value = true
288
+ error.value = null
289
+
290
+ try {
291
+ await auth.signIn.email({
292
+ email: email.value,
293
+ password: password.value,
294
+ })
295
+ await navigateTo('/account')
296
+ }
297
+ catch (cause) {
298
+ error.value = cause instanceof Error ? cause.message : 'Unable to sign in'
299
+ }
300
+ finally {
301
+ pending.value = false
302
+ }
303
+ }
304
+ </script>
305
+
306
+ <template>
307
+ <form @submit.prevent="signIn">
308
+ <input v-model="email" type="email" placeholder="Email">
309
+ <input v-model="password" type="password" placeholder="Password">
310
+ <button :disabled="pending" type="submit">
311
+ Sign in
312
+ </button>
313
+ <p v-if="error">{{ error }}</p>
314
+ </form>
315
+ </template>
316
+ ```
317
+
318
+ Use the same client for sign-up and sign-out flows.
319
+
320
+ ### 3. Read session state and Convex data in a protected page
321
+
322
+ ```vue
323
+ <!-- pages/account.vue -->
324
+ <script setup lang="ts">
325
+ import { computed } from 'vue'
326
+ import { api } from '~/backend/_generated/api'
327
+
328
+ definePageMeta({ middleware: 'auth' })
329
+
330
+ const { session } = useAuth()
331
+ const currentUser = useQuery(api.auth.getAuthUser, {})
332
+ const email = computed(() => session.value.data?.user.email)
333
+ </script>
334
+
335
+ <template>
336
+ <section>
337
+ <p>Signed in as {{ email }}</p>
338
+ <pre>{{ currentUser }}</pre>
339
+ </section>
340
+ </template>
341
+ ```
342
+
343
+ The built-in `auth` middleware protects the page, `useAuth().session` exposes the Better Auth session, and `useQuery(...)` keeps Convex data live after hydration.
344
+
345
+ ### 4. Use authenticated server helpers in Nitro handlers
346
+
347
+ ```ts
348
+ // server/api/me.ts
349
+ import { api } from '~/backend/_generated/api'
350
+
351
+ export default defineEventHandler(async (event) => {
352
+ const auth = backendAuth(event)
353
+
354
+ if (!await auth.isAuthenticated()) {
355
+ throw createError({ statusCode: 401, statusMessage: 'Unauthorized' })
356
+ }
357
+
358
+ return auth.fetchAuthQuery(api.auth.getAuthUser, {})
359
+ })
360
+ ```
361
+
362
+ `backendAuth(event)` is the Nuxt/Nitro equivalent of the official Next helper. It can get the Convex auth token, check authentication, run authenticated queries/mutations/actions, and preload authenticated query data for the client.
363
+
364
+ ```ts
365
+ // server/api/account.preload.ts
366
+ import { api } from '~/backend/_generated/api'
367
+
368
+ export default defineEventHandler((event) => {
369
+ return backendAuth(event).preloadAuthQuery(api.auth.getAuthUser, {})
370
+ })
371
+ ```
372
+
373
+ ```vue
374
+ <script setup lang="ts">
375
+ const { data: preloaded } = await useFetch('/api/account.preload')
376
+ const currentUser = usePreloadedAuthQuery(preloaded.value!)
377
+ </script>
378
+ ```
379
+
380
+ Use `usePreloadedAuthQuery` for auth-protected SSR data. It keeps the server result during auth startup, then switches to the live authenticated Convex query or clears the data if the browser is unauthenticated.
381
+
382
+ ### 5. Keep the auth route consistent if you customize it
383
+
384
+ If you change `backend.authRoute` from `/api/auth`, keep the same path in `createAuthOptions` and Convex auth config. The Nuxt proxy route, Better Auth `basePath`, and `defineBackendAuthConfig({ basePath: ... })` must all match.
385
+
386
+ ## API reference
387
+
388
+ Two ways to consume the surface:
389
+
390
+ - **Explicit imports** — `import { … } from 'nuxt-backend/…'`, declared in the package `exports` map. The `nuxt-backend/convex*` subpaths run in your **Convex backend** (`backend/`), not the Vue app.
391
+ - **Auto-imports** — registered by the module, no `import` needed. Vue composables and components are available in app code; the server utilities are available in `server/` (Nitro).
392
+
393
+ Generic helpers in the signatures below (`FunctionReference`, `FunctionArgs`, `FunctionReturnType`, `OptionalRestArgs`, `ConnectionState`, `Value`) come from `convex`; the paginated result types are re-exported from `convex/react` for parity.
394
+
395
+ ### Import tree
396
+
397
+ ```text
398
+ nuxt-backend
399
+ ├─ "nuxt-backend" ............................ Nuxt module (default) + type ModuleOptions
400
+ ├─ "nuxt-backend/convex" .................... setupAuth · createAuth · createAuthOptions
401
+ │ makeAuthApi · createBetterAuth · createBetterAuthOptions
402
+ │ + types CreateBetterAuthOptions · SetupAuthOptions
403
+ ├─ "nuxt-backend/convex/component/convex.config" ......... default: the `backend` component
404
+ ├─ "nuxt-backend/convex/component/schema" .. tables · authSchema · default (= authSchema)
405
+ ├─ "nuxt-backend/convex/component/_generated/component" .. type ComponentApi (types only)
406
+ ├─ "nuxt-backend/convex/auth.config" ....... defineBackendAuthConfig · default · type DefineBackendAuthConfigOptions
407
+ └─ "nuxt-backend/convex/test" .............. register · default ({ register, modules })
408
+
409
+ auto-imports (no import statement)
410
+ ├─ Vue composables ......... useConvex · useQuery (+ useConvexQuery, useQuery_experimental)
411
+ │ useQueries (+ useConvexQueries) · useMutation (+ useConvexMutation)
412
+ │ useAction (+ useConvexAction) · usePaginatedQuery (+ usePaginatedQuery_experimental)
413
+ │ usePreloadedQuery · usePreloadedAuthQuery · useConvexConnectionState
414
+ │ useConvexAuth · provideConvexAuth · useAuth
415
+ ├─ Vue components .......... <Authenticated> · <Unauthenticated> · <AuthLoading>
416
+ ├─ Injection ............... useNuxtApp().$convex : ConvexVueClient
417
+ └─ Server utils (Nitro) .... fetchQuery · fetchMutation · fetchAction
418
+ preloadQuery · preloadedQueryResult · backendAuth
419
+
420
+ aliases ...................... #backend · #backend/api · #backend/server
421
+ #backend/dataModel · #backend/_generated (Vite + Nitro)
422
+ ```
423
+
424
+ ### Explicit entrypoints
425
+
426
+ #### `nuxt-backend`
427
+
428
+ ```ts
429
+ import nuxtBackendModule, { type ModuleOptions } from 'nuxt-backend'
430
+
431
+ interface ModuleOptions {
432
+ url?: string
433
+ siteUrl?: string
434
+ authRoute?: string // default '/api/auth'
435
+ installation?: 'default' | 'local' // default 'default'
436
+ }
437
+ // Also augments RuntimeConfig.backend.siteUrl and
438
+ // PublicRuntimeConfig.backend.{ url, siteUrl }.
439
+ ```
440
+
441
+ #### `nuxt-backend/convex` — app-side Convex bridge
442
+
443
+ ```ts
444
+ import {
445
+ setupAuth, createAuth, createAuthOptions,
446
+ makeAuthApi, createBetterAuth, createBetterAuthOptions,
447
+ type CreateBetterAuthOptions, type SetupAuthOptions,
448
+ } from 'nuxt-backend/convex'
449
+
450
+ // Composes the wrapper + API-remount patterns for the common scaffolded case.
451
+ function setupAuth<DM extends GenericDataModel, Schema = DefaultAuthSchema>(
452
+ componentRef: ComponentRef,
453
+ queryBuilder: QueryBuilder<DM, 'public'>,
454
+ options?: SetupAuthOptions<Schema>,
455
+ ): {
456
+ authComponent: AuthComponent
457
+ createAuthOptions: (ctx: GenericCtx<DM>) => BetterAuthOptions
458
+ options: BetterAuthOptions
459
+ createAuth: (ctx: GenericCtx<DM>) => BetterAuthInstance
460
+ getAuthUser: RegisteredQuery
461
+ }
462
+
463
+ function createAuth<DM extends GenericDataModel, Schema = DefaultAuthSchema>(
464
+ ctx: GenericCtx<DM>, componentRef: ComponentRef, options?: SetupAuthOptions<Schema>,
465
+ ): BetterAuthInstance
466
+
467
+ function createAuthOptions<DM extends GenericDataModel, Schema = DefaultAuthSchema>(
468
+ ctx: GenericCtx<DM>, componentRef: ComponentRef, options?: SetupAuthOptions<Schema>,
469
+ ): BetterAuthOptions
470
+
471
+ function makeAuthApi<DM extends GenericDataModel, Schema = DefaultAuthSchema>(
472
+ componentRef: ComponentRef, queryBuilder: QueryBuilder<DM, 'public'>, options?: SetupAuthOptions<Schema>,
473
+ ): { getAuthUser: RegisteredQuery }
474
+
475
+ function createBetterAuth(database: BetterAuthAdapter, options?: CreateBetterAuthOptions): BetterAuthInstance
476
+ function createBetterAuthOptions(database: BetterAuthAdapter, options?: CreateBetterAuthOptions): BetterAuthOptions
477
+
478
+ interface CreateBetterAuthOptions {
479
+ authConfig?: AuthConfig // override the default Convex auth config
480
+ authOptions?: BetterAuthOptions // merged with package defaults
481
+ basePath?: string // default '/api/auth'
482
+ }
483
+ interface SetupAuthOptions<Schema> extends CreateBetterAuthOptions {
484
+ schema?: Schema // local Better Auth schema for hybrid/local installs
485
+ verbose?: boolean // verbose component client logs
486
+ }
487
+ ```
488
+
489
+ #### `nuxt-backend/convex/component/convex.config`
490
+
491
+ ```ts
492
+ import backend from 'nuxt-backend/convex/component/convex.config'
493
+ // default export: the `backend` Convex component → app.use(backend)
494
+ ```
495
+
496
+ #### `nuxt-backend/convex/component/schema`
497
+
498
+ ```ts
499
+ import authSchema, { tables, authSchema as schema } from 'nuxt-backend/convex/component/schema'
500
+ // tables: { user, session, account, verification, rateLimit, passkey, jwks }
501
+ // authSchema: SchemaDefinition = defineSchema(tables) (default export === authSchema)
502
+ ```
503
+
504
+ #### `nuxt-backend/convex/component/_generated/component` — types only
505
+
506
+ ```ts
507
+ import type { ComponentApi } from 'nuxt-backend/convex/component/_generated/component'
508
+ type ComponentApi<Name extends string | undefined = string | undefined>
509
+ ```
510
+
511
+ #### `nuxt-backend/convex/auth.config`
512
+
513
+ ```ts
514
+ import defineBackendAuthConfig, {
515
+ type DefineBackendAuthConfigOptions,
516
+ } from 'nuxt-backend/convex/auth.config'
517
+
518
+ function defineBackendAuthConfig(options?: DefineBackendAuthConfigOptions): AuthConfig
519
+ interface DefineBackendAuthConfigOptions {
520
+ basePath?: string // default '/api/auth'
521
+ jwks?: string
522
+ }
523
+ // default export === defineBackendAuthConfig()
524
+ ```
525
+
526
+ #### `nuxt-backend/convex/test`
527
+
528
+ ```ts
529
+ import backendTest, { register } from 'nuxt-backend/convex/test'
530
+
531
+ function register(
532
+ t: TestConvex<SchemaDefinition<GenericSchema, boolean>>,
533
+ name?: string, // default 'backend'
534
+ ): void
535
+ // default export: { register, modules }
536
+ ```
537
+
538
+ ### Auto-imported composables (Vue)
539
+
540
+ ```ts
541
+ // Client access
542
+ function useConvex(): ConvexVueClient
543
+
544
+ // Queries — returns undefined while loading; throws query errors
545
+ function useQuery<Q extends FunctionReference<'query'>>(
546
+ query: Q,
547
+ ...args: OptionalRestArgsOrSkip<Q> // reactive args; pass 'skip' to pause
548
+ ): ShallowRef<FunctionReturnType<Q> | undefined>
549
+ const useConvexQuery = useQuery
550
+
551
+ // Experimental object form — errors returned in result unless throwOnError
552
+ function useQuery_experimental<Q extends FunctionReference<'query'>, ThrowOnError extends boolean = false>(
553
+ options: { query: Q, args: MaybeRefOrGetter<FunctionArgs<Q> | 'skip'>, throwOnError?: ThrowOnError },
554
+ ): ShallowRef<UseQueryResult<FunctionReturnType<Q>, ThrowOnError>> // { status: 'pending'|'success'|'error', data?, error? }
555
+
556
+ // Dynamic set of queries
557
+ function useConvexQueries(queries: MaybeRefOrGetter<RequestForQueries>): ShallowRef<QueriesResults>
558
+ const useQueries = useConvexQueries
559
+ // RequestForQueries: Record<string, { query: FunctionReference<'query'>, args: Record<string, Value> }>
560
+ // QueriesResults: Record<string, Value | undefined | Error>
561
+
562
+ // Mutations
563
+ function useMutation<M extends FunctionReference<'mutation'>>(mutation: M): VueMutation<M>
564
+ const useConvexMutation = useMutation
565
+ interface VueMutation<M extends FunctionReference<'mutation'>> {
566
+ (...args: OptionalRestArgs<M>): Promise<FunctionReturnType<M>>
567
+ withOptimisticUpdate(update: OptimisticUpdate<FunctionArgs<M>>): VueMutation<M>
568
+ }
569
+
570
+ // Actions
571
+ function useAction<A extends FunctionReference<'action'>>(action: A): VueAction<A>
572
+ const useConvexAction = useAction
573
+ interface VueAction<A extends FunctionReference<'action'>> {
574
+ (...args: OptionalRestArgs<A>): Promise<FunctionReturnType<A>>
575
+ }
576
+
577
+ // Pagination — positional form, throws on error
578
+ function usePaginatedQuery<Q extends PaginatedQueryReference>(
579
+ query: Q,
580
+ args: MaybeRefOrGetter<PaginatedQueryArgs<Q> | 'skip'>,
581
+ options: { initialNumItems: number },
582
+ ): ShallowRef<UsePaginatedQueryReturnType<Q>>
583
+ // → { results, status: 'LoadingFirstPage'|'CanLoadMore'|'LoadingMore'|'Exhausted', isLoading, loadMore }
584
+
585
+ // Experimental — overloaded: positional (throws) OR object form (errors in result)
586
+ function usePaginatedQuery_experimental<Q extends PaginatedQueryReference>(
587
+ query: Q, args: MaybeRefOrGetter<PaginatedQueryArgs<Q> | 'skip'>, options: { initialNumItems: number },
588
+ ): ShallowRef<UsePaginatedQueryReturnType<Q>>
589
+ function usePaginatedQuery_experimental<Q extends PaginatedQueryReference, ThrowOnError extends boolean = false>(
590
+ options: MaybeRefOrGetter<UsePaginatedQueryOptions<Q, ThrowOnError>>,
591
+ ): ShallowRef<UsePaginatedQueryObjectReturnType<Q, ThrowOnError>>
592
+ // object form → { data, status: 'pending'|'success'|'error', error, canLoadMore, isLoading, loadMore }
593
+
594
+ // SSR hydration — consume a Preloaded payload, then go live on the client
595
+ function usePreloadedQuery<Q extends FunctionReference<'query'>>(preloaded: Preloaded<Q>): ShallowRef<FunctionReturnType<Q>>
596
+ function usePreloadedAuthQuery<Q extends FunctionReference<'query'>>(preloaded: Preloaded<Q>): ShallowRef<FunctionReturnType<Q> | null>
597
+
598
+ // WebSocket connection
599
+ function useConvexConnectionState(): ShallowRef<ConnectionState>
600
+
601
+ // Better Auth (the single auth service for app code)
602
+ function useAuth(initialToken?: string | null): UseAuthService
603
+ interface UseAuthService {
604
+ client: AuthClient // Better Auth client (signIn, signUp, signOut, …)
605
+ session: AuthSession // reactive Better Auth session
606
+ isAuthenticated: ComputedRef<boolean>
607
+ isLoading: ComputedRef<boolean>
608
+ fetchAccessToken: AuthTokenFetcher
609
+ authVersion: ComputedRef<string | null>
610
+ }
611
+
612
+ // Low-level Convex auth (advanced — not needed for the default Better Auth setup)
613
+ function useConvexAuth(): ConvexAuthState // { isLoading, isAuthenticated }
614
+ function provideConvexAuth(options: ConvexAuthProviderOptions): ConvexAuthState
615
+ interface ConvexAuthProviderOptions {
616
+ client: ConvexVueClient
617
+ useAuth: () => {
618
+ isLoading: MaybeRefOrGetter<boolean>
619
+ isAuthenticated: MaybeRefOrGetter<boolean>
620
+ fetchAccessToken: AuthTokenFetcher
621
+ authVersion?: MaybeRefOrGetter<unknown>
622
+ }
623
+ }
624
+ ```
625
+
626
+ ### Auto-imported components (Vue templates)
627
+
628
+ ```vue
629
+ <Authenticated> <!-- renders its slot only when authenticated -->
630
+ <Unauthenticated> <!-- renders its slot only when unauthenticated -->
631
+ <AuthLoading> <!-- renders its slot while auth state is resolving -->
632
+ ```
633
+
634
+ ### Auto-imported server utilities (Nitro / `server/`)
635
+
636
+ ```ts
637
+ function fetchQuery<Q extends FunctionReference<'query'>>(
638
+ query: Q, ...args: ArgsAndOptions<Q, NuxtConvexOptions> // (args?, options?)
639
+ ): Promise<FunctionReturnType<Q>>
640
+ function fetchMutation<M extends FunctionReference<'mutation'>>(
641
+ mutation: M, ...args: ArgsAndOptions<M, NuxtConvexOptions>
642
+ ): Promise<FunctionReturnType<M>>
643
+ function fetchAction<A extends FunctionReference<'action'>>(
644
+ action: A, ...args: ArgsAndOptions<A, NuxtConvexOptions>
645
+ ): Promise<FunctionReturnType<A>>
646
+ function preloadQuery<Q extends FunctionReference<'query'>>(
647
+ query: Q, ...args: ArgsAndOptions<Q, NuxtConvexOptions>
648
+ ): Promise<Preloaded<Q>>
649
+ function preloadedQueryResult<Q extends FunctionReference<'query'>>(preloaded: Preloaded<Q>): FunctionReturnType<Q>
650
+
651
+ interface NuxtConvexOptions {
652
+ token?: string // JWT for an authenticated call
653
+ url?: string // defaults to NUXT_PUBLIC_CONVEX_URL
654
+ }
655
+
656
+ // Per-request authenticated helper for the current H3 event
657
+ function backendAuth(event: H3Event, opts?: BackendAuthOptions): BackendAuthService
658
+ type BackendAuthOptions = GetTokenOptions & { convexSiteUrl?: string }
659
+ interface BackendAuthService {
660
+ getToken(): Promise<string | undefined>
661
+ isAuthenticated(): Promise<boolean>
662
+ handler(): Promise<Response>
663
+ preloadAuthQuery<Q extends FunctionReference<'query'>>(query: Q, args?: Q['_args']): Promise<Preloaded<Q>>
664
+ fetchAuthQuery<Q extends FunctionReference<'query'>>(query: Q, args?: Q['_args']): Promise<FunctionReturnType<Q>>
665
+ fetchAuthMutation<M extends FunctionReference<'mutation'>>(mutation: M, args?: M['_args']): Promise<FunctionReturnType<M>>
666
+ fetchAuthAction<A extends FunctionReference<'action'>>(action: A, args?: A['_args']): Promise<FunctionReturnType<A>>
667
+ }
668
+ ```
669
+
670
+ ### `ConvexVueClient`
671
+
672
+ Returned by `useConvex()` and injected as `useNuxtApp().$convex`. Most app code should prefer the composables; reach for the client for imperative one-off calls.
673
+
674
+ ```ts
675
+ class ConvexVueClient {
676
+ query<Q extends FunctionReference<'query'>>(query: Q, ...args: OptionalRestArgs<Q>): Promise<FunctionReturnType<Q>>
677
+ mutation<M extends FunctionReference<'mutation'>>(
678
+ mutation: M, ...args: ArgsAndOptions<M, VueMutationOptions<FunctionArgs<M>>>
679
+ ): Promise<FunctionReturnType<M>>
680
+ action<A extends FunctionReference<'action'>>(action: A, ...args: OptionalRestArgs<A>): Promise<FunctionReturnType<A>>
681
+ watchQuery<Q extends FunctionReference<'query'>>(query: Q, ...args: OptionalRestArgs<Q>): Watch<FunctionReturnType<Q>>
682
+ connectionState(): ConnectionState
683
+ subscribeToConnectionState(cb: (state: ConnectionState) => void): () => void
684
+ setAuth(fetchToken: AuthTokenFetcher, onChange?: (isAuthenticated: boolean) => void): void
685
+ clearAuth(): void
686
+ close(): Promise<void>
687
+ }
688
+ ```
689
+
690
+ ### Import aliases
691
+
692
+ ```ts
693
+ import { api, internal, components } from '#backend/api'
694
+ import { query, mutation, action } from '#backend/server'
695
+ import type { Doc, Id } from '#backend/dataModel'
696
+
697
+ // '#backend' → your Convex functions dir (backend/ or convex/)
698
+ // '#backend/api' → _generated/api (api, internal, components)
699
+ // '#backend/server' → _generated/server (query, mutation, action, *Ctx, ...)
700
+ // '#backend/dataModel' → _generated/dataModel (DataModel, Doc, Id, TableNames)
701
+ // '#backend/_generated' → _generated (long form, any generated file)
702
+ // All registered for both Vite and Nitro.
703
+ ```
704
+
705
+ The short aliases resolve to the same files as `#backend/_generated/*`, so use
706
+ whichever you prefer. Because `#backend/api` / `#backend/server` /
707
+ `#backend/dataModel` map straight to the generated modules, they shadow any
708
+ function file you happen to name `api.ts` / `server.ts` / `dataModel.ts` —
709
+ import those via a different name (or `#backend/_generated/...`).
710
+
711
+ ## More Documentation
712
+
713
+ See [docs/reference.md](./docs/reference.md) for usage examples, customization details, architecture notes, and the development workflow.
714
+
715
+ ## Contributing
716
+
717
+ 1. Clone this repository
718
+ 2. Install dependencies using `pnpm install`
719
+ 3. Prepare for development using `pnpm dev:prepare`
720
+ 4. Start development server using `pnpm dev`
721
+
722
+ We follow conventional commits (Renovate PRs do too). After CI is green on `main`, run `pnpm release` locally to cut a new release (release-it updates CHANGELOG.md, creates a git tag, and can create a GitHub Release). Pushing the tag triggers the automated release workflow which:
723
+
724
+ - Creates (or updates) a rich GitHub Release with conventional commit grouping and an explicit "Thank you to contributors" section (via `changelogithub` + fallback `gh release create`).
725
+ - Publishes to npm with provenance (OIDC recommended).
726
+
727
+ See `.github/workflows/release.yml` and `.github/release.yml` for the exact configuration.
728
+
729
+ ## License
730
+
731
+ [MIT](./LICENSE)
732
+
733
+ <!-- Badges -->
734
+ [npm-version-src]: https://img.shields.io/npm/v/nuxt-backend/latest.svg?style=flat&colorA=020420&colorB=00DC82
735
+ [npm-version-href]: https://npmjs.com/package/nuxt-backend
736
+
737
+ [npm-downloads-src]: https://img.shields.io/npm/dm/nuxt-backend.svg?style=flat&colorA=020420&colorB=00DC82
738
+ [npm-downloads-href]: https://npm.chart.dev/nuxt-backend
739
+
740
+ [license-src]: https://img.shields.io/npm/l/nuxt-backend.svg?style=flat&colorA=020420&colorB=00DC82
741
+ [license-href]: https://npmjs.com/package/nuxt-backend
742
+
743
+ [nuxt-src]: https://img.shields.io/badge/Nuxt-020420?logo=nuxt
744
+ [nuxt-href]: https://nuxt.com