Plain Vue and Vite
Use the Better Convex composables in a Vue app without Nuxt.
@lupinum/better-convex-vue gives a plain Vue app the same browser composables
that the Nuxt module uses: queries, pagination, mutations, actions, forms, file
uploads, and connection state. It clears user data when the user changes.
It does not depend on Nuxt or Better Auth. Use the Nuxt module when you need server rendering, Nuxt server routes, or the built-in Better Auth setup.
Install
Create a Vite app with Vue and TypeScript, or skip this step in an existing app:
pnpm create vite@latest my-vue-app --template vue-ts
cd my-vue-app
pnpm installAdd the package and Convex:
pnpm add @lupinum/better-convex-vue convex@^1.42.2 vue@^3.5.0The package needs vue >=3.5.0 <4 and convex >=1.42.2 <2. When pnpm
reports that it ignored the build script of esbuild, run pnpm approve-builds
and allow it.
Start Convex
Run npx convex dev in the project folder and keep it running. On the first
run it asks you to log in or to start without an account; without an account,
Convex runs on your computer. It creates the convex/ folder, writes
VITE_CONVEX_URL to .env.local, and keeps convex/_generated/api up to date
while it runs. A cloud deployment URL ends in .convex.cloud; a local one is
http://127.0.0.1:3210.
Anonymous application
Install one plugin at the Vue application root:
import { createApp } from 'vue'
import { createBetterConvex } from '@lupinum/better-convex-vue'
import App from './App.vue'
const app = createApp(App)
app.use(
createBetterConvex({
convexUrl: import.meta.env.VITE_CONVEX_URL,
}),
)
app.mount('#app')Add the Convex functions that the component below uses:
import { defineSchema, defineTable } from 'convex/server'
import { v } from 'convex/values'
export default defineSchema({
notes: defineTable({ title: v.string() }),
})import { ConvexError, v } from 'convex/values'
import { mutation, query } from './_generated/server'
// Public on purpose: this anonymous example lets anyone read and rename notes.
// A real application checks the user and their permission in each function.
export const list = query({
args: {},
handler: (ctx) => ctx.db.query('notes').order('desc').take(50),
})
export const rename = mutation({
args: { id: v.id('notes'), title: v.string() },
handler: async (ctx, { id, title }) => {
const trimmed = title.trim().slice(0, 200)
if (!trimmed) throw new ConvexError({ code: 'EMPTY_TITLE', message: 'Title is empty' })
await ctx.db.patch(id, { title: trimmed })
},
})Open the dashboard with npx convex dashboard and add a note (Data → notes
→ Add), so the list is not empty.
When your application has sign-in, do not keep these public functions. Replace them with the functions under Authentication with any provider, which check the user.
Then use the composables in components. They return refs right away. You do not await them:
<script setup lang="ts">
import { api } from '../../convex/_generated/api'
import { useConvexMutation, useConvexQuery } from '@lupinum/better-convex-vue'
const { data: notes, status, error } = useConvexQuery(api.notes.list, {})
const { mutate: renameNote, pending: renaming } = useConvexMutation(api.notes.rename)
</script>
<template>
<p v-if="status === 'pending'">Loading…</p>
<p v-else-if="error">Could not load notes.</p>
<ul v-else>
<li v-for="note in notes" :key="note._id">
<button :disabled="renaming" @click="renameNote({ id: note._id, title: `${note.title}!` })">
{{ note.title }}
</button>
</li>
</ul>
</template>Render the component from the root:
<script setup lang="ts">
import Notes from './components/Notes.vue'
</script>
<template>
<Notes />
</template>Start the app in a second terminal with pnpm dev, and open the address that
Vite prints. Open it in two tabs and rename a note in one. The other tab updates
without a reload.
A query with args: {} may omit the arguments. Every other query needs an
argument object or 'skip'. Pass a computed value that returns 'skip' to
pause a query. A skipped query stops its subscription and clears its data.
Query data is undefined until a value exists. A backend null result is
successful data, not a loading or skip sentinel.
Wait for data before a page shows
A page that loads its data after it appears flashes empty and then moves its
content. To show the page only when its data exists, await its queries and
render it inside Vue's <Suspense>. A component that awaits does not render
at all without a <Suspense> above it.
This section uses Vue Router. Install it:
pnpm add vue-routerCreate the router with the notes page:
import { createRouter, createWebHistory } from 'vue-router'
import NotesPage from './pages/NotesPage.vue'
export const router = createRouter({
history: createWebHistory(),
routes: [{ path: '/', component: NotesPage }],
})Install it in src/main.ts: import router from ./router and add
app.use(router) before app.mount('#app'). Then replace src/App.vue, so
each page renders inside <Suspense>. The v-if keeps <Suspense> out until
the router has its first page. Without it, Vue logs a warning on every page
load.
<template>
<RouterView v-slot="{ Component }">
<Suspense v-if="Component">
<component :is="Component" />
</Suspense>
</RouterView>
</template><script setup lang="ts">
import { api } from '../../convex/_generated/api'
import { useConvexQuery } from '@lupinum/better-convex-vue'
const { data: notes, error } = await useConvexQuery(api.notes.list, {})
</script>
<template>
<p v-if="error">Could not load notes.</p>
<ul v-else>
<li v-for="note in notes" :key="note._id">{{ note.title }}</li>
</ul>
</template>When the route shows a different page component, <Suspense> keeps the
previous page on the screen. It shows the new page when every awaited query in
it, also in its child components, has its first result or error. The refs stay
live after the await. A navigation to the same component with other parameters
reuses the page and does not wait again; it shows pending while the new
arguments load.
- Start all queries of a component before you await them, then use
await Promise.all([first, second]). Each separateawaitwaits for the query before it. - A child component starts its queries only after its parent's await is finished.
- The await never rejects. Read
errorfor a failure. - The await waits while authentication loads. It does not wait for a skipped
query, a query with
immediate: false, or anauth: 'required'query without a signed-in user or after an authentication error.
Vue marks <Suspense> as experimental.
Load data before a navigation finishes
<Suspense> waits after the router changed the URL, and child components load
only after their parent. To load a page's data before the navigation finishes,
preload it in a router guard. This needs Vue Router 4.2 or later. In this
example, ProjectPage.vue, api.projects.get, and api.tasks.list stand for
your own page and its queries:
import { preloadConvexQuery } from '@lupinum/better-convex-vue'
import { createRouter, createWebHistory } from 'vue-router'
import { api } from '../convex/_generated/api'
import type { Id } from '../convex/_generated/dataModel'
import NotesPage from './pages/NotesPage.vue'
import ProjectPage from './pages/ProjectPage.vue'
export const router = createRouter({
history: createWebHistory(),
routes: [
{ path: '/', component: NotesPage },
{ path: '/projects/:id', name: 'project', component: ProjectPage },
],
})
router.beforeResolve(async (to) => {
if (to.name === 'project') {
const id = to.params.id as Id<'projects'>
await Promise.all([
preloadConvexQuery(api.projects.get, { id }),
preloadConvexQuery(api.tasks.list, { projectId: id }),
])
}
})The queries load in parallel. When the page and its child components call
useConvexQuery with the same function, arguments, and auth, they start with
the result. The page shows complete on its first render, and the router can
scroll to its content.
- Start every preload before the first
awaitin the guard, as inPromise.allabove. After anawait, Vue Router no longer provides the app, andpreloadConvexQuerythrows. preloadConvexQueryresolves when the first result or error exists, or after 5 seconds without one, for example while the app is offline. It never rejects for a query failure. The page's own query reports the error one moment after its first render.- The subscription stays open for 5 seconds after the preload resolves, also when the navigation is cancelled. A page that mounts later loads its data again.
- Preload only data that the page reads on its first render.
Client options
Pass supported ConvexClient options with clientOptions:
app.use(
createBetterConvex({
convexUrl: import.meta.env.VITE_CONVEX_URL,
clientOptions: { verbose: import.meta.env.DEV },
}),
)clientOptions accepts verbose, webSocketConstructor,
skipConvexDeploymentUrlCheck, and unsavedChangesWarning. Any other key
throws a TypeError, because the package manages auth and client replacement.
unsavedChangesWarning defaults to false. The type is
BetterConvexClientOptions. An embedded app that uses attachment cannot pass
clientOptions.
Experimental subscription retention
Pass experimental.keepAlive to the plugin that owns the clients:
app.use(
createBetterConvex({
convexUrl: import.meta.env.VITE_CONVEX_URL,
experimental: { keepAlive: { ms: 60_000, max: 30 } },
}),
)This option keeps stopped query subscriptions open for ms milliseconds, up to
max retained handles. Start with the values above. Both must be positive safe
integers. Returning to the same query can show its current data at once while
it is retained. A user change or application disposal releases all retained
subscriptions. The dedicated anonymous auth: 'none' transport is not retained.
Retention is off by default and is not covered by semantic versioning. Each
retained query is re-run by Convex when its data changes, so retention can
increase backend work. An embedded application uses the owning application's
configuration; it cannot set experimental with attachment.
Authentication with any provider
The Vue package works with any identity provider. You write an auth adapter. The adapter reports the provider's session state and returns a short-lived Convex token:
import type { BetterConvexAuthAdapter } from '@lupinum/better-convex-vue'
// Replace this with your identity provider's browser SDK.
interface ProviderSession {
status: 'pending' | 'authenticated' | 'anonymous' | 'error'
userId: string | null
generation: number
error: Error | null
}
declare const provider: {
session(): ProviderSession
onChange(listener: () => void): () => void
refresh(): Promise<void>
}
export const auth: BetterConvexAuthAdapter = {
snapshot: () => {
const session = provider.session()
return {
status: session.status,
identityKey: session.userId,
sessionGeneration: session.generation,
error: session.error,
}
},
subscribe: (listener) => provider.onChange(listener),
fetchToken: async () => {
// Your backend returns a Convex token for the current session.
const response = await fetch('/api/convex-token', { credentials: 'include' })
return response.ok ? ((await response.json()) as { token: string }).token : null
},
refreshSession: () => provider.refresh(),
}identityKeyis a stable user ID that is not secret. The package uses it only to keep one user's data apart from another's.sessionGenerationmust increase whenever the session changes, including a new session for the same user.- Neither value is a role or a permission.
fetchTokenreturns a token for the session in the current snapshot, ornull. If it returns a cached token, the token must belong to that session and not be expired. The client keeps the first confirmed token until a refresh shortly before itsexp, so the token needsiatandexpclaims.- Convex reports
nullas signed out. When your token endpoint fails for a temporary reason (429, 5xx, network),fetchTokenmay wait and try again before it answers. It must settle within 60 seconds, and Convex must confirm the returned token within 10 seconds; otherwise the identity fails closed. When Convex forces a refresh (forceRefreshToken: true), return a new token, not the cached one: Convex stops refreshing when it gets the same token back. tokenRefreshLeewaySeconds(optional) sets how many seconds beforeexpConvex asks for the next token. The default is Convex's 10. A longer leeway givesfetchTokentime to wait out a failure while the current token still works. Keep it well below the token lifetime.
Install the adapter in src/main.ts: import auth from ./convex-auth and
pass it to the plugin. Keep the rest of the file:
import { auth } from './convex-auth'
app.use(
createBetterConvex({
convexUrl: import.meta.env.VITE_CONVEX_URL,
auth,
}),
)Your backend issues the Convex token. Never put provider secrets, cookies, refresh tokens, deployment keys, or signing keys in the Vite bundle. Check permissions in every protected Convex function.
With sign-in, no function of the notes example stays public. Store the owner on each note. Convex rejects the new schema while a note without an owner exists, so delete those notes in the dashboard first:
import { defineSchema, defineTable } from 'convex/server'
import { v } from 'convex/values'
export default defineSchema({
notes: defineTable({ ownerId: v.string(), title: v.string() }).index('by_owner', ['ownerId']),
})Replace convex/notes.ts. Each function reads the user from the Convex token
and uses only the notes of that user:
import { ConvexError, v } from 'convex/values'
import { mutation, query } from './_generated/server'
export const list = query({
args: {},
handler: async (ctx) => {
const identity = await ctx.auth.getUserIdentity()
if (!identity) {
throw new ConvexError({ code: 'UNAUTHENTICATED', message: 'Authentication required' })
}
return await ctx.db
.query('notes')
.withIndex('by_owner', (q) => q.eq('ownerId', identity.subject))
.order('desc')
.take(50)
},
})
export const rename = mutation({
args: { id: v.id('notes'), title: v.string() },
handler: async (ctx, { id, title }) => {
const identity = await ctx.auth.getUserIdentity()
const note = await ctx.db.get(id)
// The same error for a missing note and for a note of another user.
if (!identity || !note || note.ownerId !== identity.subject) {
throw new ConvexError({ code: 'NOTE_NOT_FOUND', message: 'Note not found' })
}
const trimmed = title.trim().slice(0, 200)
if (!trimmed) throw new ConvexError({ code: 'EMPTY_TITLE', message: 'Title is empty' })
await ctx.db.patch(id, { title: trimmed })
},
})ctx.auth.getUserIdentity()works with every auth provider. It does not check that the session is still valid. With the Nuxt module's auth, useauth.requireUser(ctx)instead (see Protect data).- A mutation that creates a note sets
ownerIdfromidentity.subject, never from an argument. - In
Notes.vue, pass{ auth: 'required' }as the third argument ofuseConvexQuery. The query then does not run while nobody is signed in.
Embedded Vue applications
A Nuxt app can share its Convex connection with a separately built Vue app that
runs on the same page. Install @lupinum/better-convex-vue in the
Nuxt app too. Then read the attachment in a Nuxt component and pass it to the embedded
app:
<script setup lang="ts">
import { createApp, type App } from 'vue'
import { createBetterConvex } from '@lupinum/better-convex-vue'
import EmbeddedApp from './EmbeddedApp.vue'
let embeddedApp: App | undefined
if (import.meta.client) {
// useConvexAttachment() throws on the server.
const attachment = useConvexAttachment()
onMounted(() => {
embeddedApp = createApp(EmbeddedApp)
embeddedApp.use(createBetterConvex({ attachment }))
embeddedApp.mount('#embedded')
})
onBeforeUnmount(() => embeddedApp?.unmount())
}
</script>
<template>
<div id="embedded" />
</template>The attachment lets the embedded app run queries and mutations as the current user. It contains no token, cookie, or session. Do not create a second Convex client in the embedded app, and do not pass credentials to it.
What plain Vue does not include
- Server rendering and hydration
- Nuxt server routes and
serverConvex() - Better Auth setup and the auth proxy
- Route middleware
- An MCP server
- Roles and permissions
Use @lupinum/better-convex-nuxt for the Nuxt features. Use
@lupinum/better-convex-agents for an MCP server.