### Basic Mutation Example Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/auto-imports.md Simple implementation of a mutation within a Vue component setup function. ```ts export default defineComponent({ setup() { const { mutate: addTask } = useConvexMutation(api.tasks.add) const handleAddTask = async (text) => { await addTask({ text }) } return { handleAddTask } } }) ``` -------------------------------- ### Module Setup Processing Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/implementation-details.md The setup function logic for updating runtime configuration with module options. ```typescript setup(options) { // options = { url: '...' } updateRuntimeConfig({ public: { convex: options } }) // Now in runtimeConfig.public.convex = { url: '...' } } ``` -------------------------------- ### ConvexClient Authentication Plugin Setup Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/types.md Example of configuring authentication within a Nuxt plugin using an auth provider. ```ts export default defineNuxtPlugin(() => { const convex = useConvexClient() const { getToken } = useAuth() // from Clerk or similar convex.setAuth(async () => { return await getToken({ template: 'convex', skipCache: false, }) }) }) ``` -------------------------------- ### Configure Authentication Plugin Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/nuxt-integration.md Example of setting up an authentication plugin that depends on the initialized Convex client. ```ts // plugins/01-convex-base.ts (implicit, from module) // Plugin initializes convex-vue // plugins/02-convex-clerk.ts (user-created) export default defineNuxtPlugin(() => { const convex = useConvexClient() // Now available from module plugin const auth = useAuth() // From Clerk convex.setAuth(async () => { return auth.getToken.value(...) }) }) ``` -------------------------------- ### Initialize Argument Objects Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/types.md Examples of initializing argument objects with varying content for queries and mutations. ```ts // Empty arguments const args = {} // With values const args = { userId: 'user123', limit: 10, } // Typed arguments for specific queries const args = { id: 'task_id_123', } ``` -------------------------------- ### Start Nuxt development server Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/nuxt-integration.md Run the development server to trigger automatic module initialization and enable auto-imports. ```bash # Start dev server with module npx nuxi dev # Module initializes automatically # Auto-imports available # Plugin runs during startup ``` -------------------------------- ### Install Convex Nuxt Manually Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/getting-started.md Install the required dependencies using your preferred package manager. ```bash npm install convex-nuxt convex-vue # or pnpm add convex-nuxt convex-vue # or yarn add convex-nuxt convex-vue ``` -------------------------------- ### Convex Nuxt Configuration Example Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/api-reference/plugin.md Shows the required configuration in nuxt.config.ts and the internal resolution flow used by the plugin. ```ts // nuxt.config.ts export default defineNuxtConfig({ modules: ['convex-nuxt'], convex: { url: 'https://my-app.convex.dev' } }) // Inside plugin execution: // 1. Module sets: runtimeConfig.public.convex = { url: 'https://my-app.convex.dev' } // 2. Plugin reads: const options = useRuntimeConfig().public.convex // 3. Plugin uses: nuxtApp.vueApp.use(convexVue, options) ``` -------------------------------- ### User Configuration Definition Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/implementation-details.md Example of how to define the convex module configuration in nuxt.config. ```typescript export default defineNuxtConfig({ modules: ['convex-nuxt'], convex: { url: '...' } }) ``` -------------------------------- ### Install Convex Nuxt Module Source: https://github.com/chris-visser/convex-nuxt/blob/main/README.md Use the nuxi CLI to add the module to your Nuxt project. ```bash npx nuxi module add convex-nuxt ``` -------------------------------- ### Simple Static HTTP Query Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/auto-imports.md Example of fetching static data using the HTTP query composable. ```ts export default defineComponent({ setup() { const { data: config } = useConvexHttpQuery(api.config.get, {}) return { config } } }) ``` -------------------------------- ### Access Core Composables Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/INDEX.md Usage examples for the four auto-imported composables provided by the module. ```typescript const client = useConvexClient() ``` ```typescript const { data } = useConvexQuery(api.tasks.get, {}) ``` ```typescript const { mutate } = useConvexMutation(api.tasks.add) ``` ```typescript const { data } = useConvexHttpQuery(api.config.get, {}) ``` -------------------------------- ### Using Convex Composables without Explicit Imports Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/auto-imports.md Demonstrates accessing Convex client, queries, and mutations directly within a component setup function without manual import statements. ```ts // In a component, composable, or anywhere in the app export default defineComponent({ setup() { const client = useConvexClient() const { data } = useConvexQuery(api.tasks.get, {}) const { mutate } = useConvexMutation(api.tasks.add) return { client, data, mutate } } }) ``` -------------------------------- ### Mutation in Form Submission Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/auto-imports.md Example of using a mutation within a Vue script setup block for form handling. ```vue ``` -------------------------------- ### Execute Convex Queries Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/getting-started.md Examples for fetching data using static and reactive arguments in Nuxt components. ```ts const { data } = useConvexQuery(api.tasks.get, {}) ``` ```ts const userId = ref('user123') const { data: userTasks } = useConvexQuery( api.tasks.getByUser, () => ({ userId: userId.value }) ) ``` ```ts const filterId = ref('all') const { data } = useConvexQuery(api.tasks.getByFilter, () => ({ filterId: filterId.value, })) watch(filterId, () => { // Query automatically re-runs when filterId changes }) ``` -------------------------------- ### Install Clerk dependency Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/advanced-topics.md Install the required Clerk Nuxt package via npm. ```bash npm install @clerk/nuxt ``` -------------------------------- ### Install convex-vue peer dependency Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/getting-started.md Install the required peer dependency to resolve TypeScript errors. ```bash npm install convex-vue ``` -------------------------------- ### Convex Composable Usage Examples Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/00_START_HERE.md Quick reference for the four primary composables provided by the module. ```typescript const client = useConvexClient() ``` ```typescript const { data } = useConvexQuery(api.tasks.get, {}) ``` ```typescript const { mutate } = useConvexMutation(api.tasks.add) ``` ```typescript const { data } = useConvexHttpQuery(api.config, {}) ``` -------------------------------- ### Implement Suspense for Async Components Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/nuxt-integration.md Use Suspense to ensure Nuxt awaits async setup functions before rendering, preventing hydration mismatches. ```vue ``` -------------------------------- ### Readonly Data Query Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/auto-imports.md Example of using HTTP queries for static or readonly content. ```ts export default defineComponent({ setup() { const { data: staticContent } = useConvexHttpQuery(api.content.getStatic, {}) return { staticContent } } }) ``` -------------------------------- ### Register Vue Plugin Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/api-reference/plugin.md Installs the convex-vue plugin into the Nuxt Vue application instance. ```ts nuxtApp.vueApp.use(convexVue, options) ``` -------------------------------- ### Read Configuration in Components Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/configuration.md Access the Convex URL within a Vue component setup function using useRuntimeConfig. ```ts import { useRuntimeConfig } from '#app' export default defineComponent({ setup() { const config = useRuntimeConfig() const convexUrl = config.public.convex.url console.log(`Connected to: ${convexUrl}`) return {} } }) ``` -------------------------------- ### Register Module in Nuxt Config Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/getting-started.md Add the module to your nuxt.config.ts file after manual installation. ```typescript export default defineNuxtConfig({ modules: ['convex-nuxt'], }) ``` -------------------------------- ### Define Nuxt Module Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/api-reference/module.md The main module definition for convex-nuxt, specifying the meta information and setup function. ```ts export default defineNuxtModule({ meta: { name: 'convex-nuxt', configKey: 'convex', }, defaults: {}, setup(options) { /* ... */ }, }) ``` -------------------------------- ### Build Nuxt project Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/nuxt-integration.md Execute the build command to bundle the module and optimize plugin code for production. ```bash # Build includes module processing npx nuxi build # Module is bundled or referenced as peer dependency # Plugin code transformed for production ``` -------------------------------- ### Verify Client Initialization Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/advanced-topics.md Use a Nuxt plugin to verify that the Convex client and runtime configuration are correctly initialized. ```ts export default defineNuxtPlugin(() => { const client = useConvexClient() console.log('Convex client initialized:', client) // Verify config const config = useRuntimeConfig() console.log('Convex config:', config.public.convex) }) ``` -------------------------------- ### Define Project Structure Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/getting-started.md Recommended directory layout for a Nuxt application integrated with Convex. ```text my-nuxt-app/ ├── nuxt.config.ts ├── app.vue ├── convex/ │ ├── tasks.ts # Your Convex functions │ └── tsconfig.json ├── src/ │ └── components/ │ ├── TaskList.vue │ └── TaskForm.vue └── plugins/ └── convex-clerk.ts # Auth setup (optional) ``` -------------------------------- ### Using realtime queries Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/advanced-topics.md Use useConvexQuery for realtime updates instead of the non-reactive useConvexHttpQuery. ```ts // ❌ Won't update realtime const { data } = useConvexHttpQuery(api.tasks.get, {}) // ✅ Updates realtime const { data } = useConvexQuery(api.tasks.get, {}) ``` -------------------------------- ### Local Development Commands Source: https://github.com/chris-visser/convex-nuxt/blob/main/README.md Common commands for managing dependencies, development, and testing of the module. ```bash # Install dependencies bun install # Generate type stubs bun run dev:prepare # Develop with the playground bun run dev # Build the playground bun run dev:build # Run ESLint bun run lint # Run Vitest bun run test bun run test:watch # Release new version bun run release ``` -------------------------------- ### Project Documentation Map Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/00_START_HERE.md Visual representation of the documentation structure for new, developer, and advanced user flows. ```text START HERE ↓ Choose your path below... NEW USER FLOW DEVELOPER FLOW ADVANCED FLOW ├─ README.md ├─ api-reference/ ├─ implementation-details.md ├─ getting-started.md ├─ types.md ├─ nuxt-integration.md ├─ configuration.md ├─ auto-imports.md ├─ advanced-topics.md └─ auto-imports.md └─ [use in projects] └─ [solve complex issues] ``` -------------------------------- ### Generate TypeScript types Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/nuxt-integration.md Run the prepare command to ensure TypeScript definitions are generated for the project. ```bash # Nuxt generates type definitions npx nuxi prepare ``` -------------------------------- ### UseQueryReturn Usage in Vue Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/types.md Shows how to consume query results and handle loading/error states in a Vue template. ```ts const { data, pending, error } = useConvexQuery(api.tasks.get, {}) // In template
Loading...
Error: {{ error.message }}
``` -------------------------------- ### ConvexClient Authentication Usage Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/types.md Demonstrates how to set an authentication token provider on the Convex client. ```ts const client = useConvexClient() // Set authentication token provider client.setAuth(async () => { return await getTokenFromAuthProvider() }) ``` -------------------------------- ### Configure Clerk Authentication Plugin Source: https://github.com/chris-visser/convex-nuxt/blob/main/README.md Create a plugin to pass authentication tokens from Clerk to the Convex client. ```ts export default defineNuxtPlugin(() => { const convex = useConvexClient() // from convex-nuxt const auth = useAuth() // from @clerk/nuxt // Whenever Convex needs a token, it will call this function const getToken = async () => { return auth.getToken.value({ template: 'convex', skipCache: false, }) } convex.setAuth(getToken) }) ``` -------------------------------- ### Implement Pagination Pattern Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/getting-started.md Use reactive references to drive paginated queries. ```ts const page = ref(0) const pageSize = ref(10) const { data: tasks } = useConvexQuery( api.tasks.getPaginated, () => ({ page: page.value, pageSize: pageSize.value, }) ) ``` -------------------------------- ### Module Configuration Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/api-reference/module.md The module is configured in nuxt.config.ts using the 'convex' key, accepting ConvexVueOptions to initialize the Convex client. ```APIDOC ## Module Configuration ### Description The module is registered in `nuxt.config.ts` under the `convex` key. It accepts a configuration object of type `ConvexVueOptions` which is passed to the underlying `convex-vue` plugin. ### Configuration Key `convex` ### Options - **options** (`ConvexVueOptions`) - Optional - Configuration object containing Convex settings. ``` -------------------------------- ### Define Environment Variable Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/configuration.md Set the Convex URL in a .env file using the NUXT_ prefix for automatic loading. ```bash # .env.local NUXT_CONVEX_URL=https://my-app.convex.dev ``` -------------------------------- ### Query Caching and Realtime Updates Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/advanced-topics.md Use useConvexHttpQuery for static data to reduce overhead, and useConvexQuery for data requiring real-time updates. ```ts // HTTP query - fetched once, cached const { data: config } = useConvexHttpQuery(api.config.get, {}) // Realtime query - updates in real-time const { data: tasks } = useConvexQuery(api.tasks.get, {}) ``` -------------------------------- ### Configure Static Site Generation Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/advanced-topics.md Configure route rules in nuxt.config.ts to enable SWR caching for static generation. ```typescript // nuxt.config.ts export default defineNuxtConfig({ modules: ['convex-nuxt'], convex: { url: process.env.NUXT_CONVEX_URL, }, routeRules: { // Cache static pages for 1 hour '/': { swr: 3600 }, '/about': { swr: 3600 }, '/tasks/**': { swr: 3600 }, }, }) ``` -------------------------------- ### Environment Variable Configuration Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/configuration.md Using environment variables to manage the Convex deployment URL across different environments. ```ts // nuxt.config.ts export default defineNuxtConfig({ modules: ['convex-nuxt'], convex: { url: process.env.NUXT_CONVEX_URL, }, }) ``` ```text NUXT_CONVEX_URL=https://my-app.convex.dev ``` ```bash export NUXT_CONVEX_URL=https://my-app.convex.dev npx nuxi dev ``` -------------------------------- ### Execute Mutation with useConvexMutation Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/types.md Basic implementation showing how to destructure the mutation hook and handle the asynchronous mutate function. ```ts const { mutate, pending, error } = useConvexMutation(api.tasks.add) const handleSubmit = async (text) => { try { const result = await mutate({ text }) console.log('Created:', result) } catch (err) { console.error('Failed:', err) } } ``` -------------------------------- ### Create data with useConvexMutation Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/README.md Execute mutations to modify data. Wrap in a try-catch block to handle potential errors during the mutation process. ```ts const { mutate: addTask, pending, error } = useConvexMutation(api.tasks.add) const handleSubmit = async (text) => { try { await addTask({ text }) } catch (err) { console.error('Failed:', err) } } ``` -------------------------------- ### Implement pagination for Convex queries Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/advanced-topics.md Calculates skip and take offsets based on reactive page and pageSize refs. ```ts // composables/usePaginatedTasks.ts export const usePaginatedTasks = () => { const page = ref(0) const pageSize = ref(10) const { data: tasks, pending } = useConvexQuery( api.tasks.getPaginated, () => ({ skip: page.value * pageSize.value, take: pageSize.value, }) ) const nextPage = () => page.value++ const prevPage = () => { if (page.value > 0) page.value-- } return { tasks, pending, page, pageSize, nextPage, prevPage } } ``` -------------------------------- ### Implement Auth0 authentication plugin Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/advanced-topics.md Create a Nuxt plugin to sync the Auth0 access token with the Convex client. ```typescript export default defineNuxtPlugin(() => { const convex = useConvexClient() const { getAccessTokenSilently } = useAuth0() convex.setAuth(async () => { try { const token = await getAccessTokenSilently() return token } catch (error) { console.error('Failed to get token:', error) return null } }) }) ``` -------------------------------- ### Package Exports Configuration Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/implementation-details.md The package.json exports field defining entry points and type definitions. ```json { "main": "./dist/module.mjs", "exports": { ".": { "types": "./dist/types.d.mts", "import": "./dist/module.mjs" } } } ``` -------------------------------- ### Generate Convex types Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/getting-started.md Run the development command to generate necessary Convex types. ```bash convex dev ``` -------------------------------- ### Access Convex Client with useConvexClient Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/auto-imports.md Provides the initialized Convex client instance for direct API operations. ```ts const client = useConvexClient() ``` ```ts function useConvexClient(): ConvexClient ``` ```ts export default defineComponent({ setup() { const client = useConvexClient() // client is the ConvexClient instance return {} } }) ``` ```ts export default defineNuxtPlugin(() => { const convex = useConvexClient() const auth = useAuth() // from Clerk or similar const getToken = async () => { return auth.getToken.value({ template: 'convex', skipCache: false, }) } convex.setAuth(getToken) }) ``` -------------------------------- ### useConvexClient() Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/README.md Returns the active Convex client instance. ```APIDOC ## useConvexClient() ### Description Access the underlying Convex client instance for direct interaction. ### Returns - **ConvexClient** - The active Convex client instance. ``` -------------------------------- ### Configure Convex via Environment Variables Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/getting-started.md Use environment variables for configuration to keep sensitive URLs out of your source code. ```text NUXT_CONVEX_URL=https://your-convex-url.convex.dev ``` ```typescript export default defineNuxtConfig({ modules: ['convex-nuxt'], convex: { url: process.env.NUXT_CONVEX_URL, }, }) ``` -------------------------------- ### Implement custom authentication plugin Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/advanced-topics.md Create a Nuxt plugin to sync a custom auth store token with the Convex client. ```typescript export default defineNuxtPlugin(() => { const convex = useConvexClient() const authStore = useAuthStore() convex.setAuth(async () => { // Return token from your custom auth system return authStore.getToken() }) }) ``` -------------------------------- ### Update Runtime Configuration Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/configuration.md Use this pattern to define public configuration accessible on the client side. ```ts updateRuntimeConfig({ public: { convex: options, // This is public }, }) ``` -------------------------------- ### Mutation with Error Handling Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/auto-imports.md Demonstrates wrapping the mutation call in a try-catch block to handle potential errors. ```ts export default defineComponent({ setup() { const { mutate: deleteTask, pending, error } = useConvexMutation(api.tasks.remove) const handleDelete = async (id) => { try { await deleteTask({ id }) console.log('Task deleted') } catch (err) { console.error('Failed to delete:', err) } } return { handleDelete, pending, error } } }) ``` -------------------------------- ### UseQueryReturn Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/types.md Reactive state container for query results returned by useConvexQuery or useConvexHttpQuery. ```APIDOC ## UseQueryReturn ### Description A reactive state container for query results. All properties are Vue refs that update automatically when the query state changes. ### Properties - **data** (Ref) - The query result, undefined while loading. - **pending** (Ref) - Loading state; true while the query is executing. - **error** (Ref) - Error object if the query fails, undefined on success. ### Usage ```ts const { data, pending, error } = useConvexQuery(api.tasks.get, {}); // In template
Loading...
Error: {{ error.message }}
  • {{ item.text }}
``` ``` -------------------------------- ### Manage Async Components with Suspense Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/advanced-topics.md Use Suspense to handle loading states for async components during SSR. ```vue ``` ```vue ``` -------------------------------- ### Implement Search Pattern Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/getting-started.md Use a reactive search term to trigger dynamic queries. ```ts const searchTerm = ref('') const { data: results } = useConvexQuery( api.tasks.search, () => ({ query: searchTerm.value, }) ) ``` -------------------------------- ### Handle Mutation Errors Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/types.md Demonstrates two approaches for error handling: catching the promise rejection or observing the reactive error ref. ```ts // Method 1: Catch thrown error await mutate({ text }).catch(err => console.error(err)) // Method 2: Check error ref const { error } = useConvexMutation(...) watchEffect(() => { if (error.value) { console.error(error.value) } }) ``` -------------------------------- ### Create Data Fetching Composable Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/getting-started.md Encapsulate query logic into a reusable composable for cleaner component code. ```ts // composables/useTasks.ts export const useTasks = () => { const { data: tasks, pending, error } = useConvexQuery(api.tasks.get, {}) return { tasks, pending, error } } ``` ```ts export default defineComponent({ setup() { const { tasks } = useTasks() return { tasks } } }) ``` -------------------------------- ### Configure Custom Auth Providers Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/getting-started.md Implement a generic Nuxt plugin to provide authentication tokens to Convex from any provider. ```ts export default defineNuxtPlugin(() => { const convex = useConvexClient() const auth = useYourAuthProvider() convex.setAuth(async () => { return await auth.getToken() }) }) ``` -------------------------------- ### Comparison of Query Types Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/auto-imports.md Side-by-side comparison of real-time queries versus static HTTP queries. ```ts // Real-time query - updates when data changes on the server const { data: tasks1 } = useConvexQuery(api.tasks.get, {}) // HTTP query - fetches once, no realtime updates const { data: tasks2 } = useConvexHttpQuery(api.tasks.get, {}) ``` -------------------------------- ### Configure Authentication Token in Nuxt Plugin Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/api-reference/plugin.md Use this pattern to set authentication tokens for the Convex client before making requests. Requires an existing authentication provider like Clerk. ```ts // plugins/convex-auth.ts export default defineNuxtPlugin(() => { const convex = useConvexClient() const auth = useAuth() // from Clerk or other auth provider const getToken = async () => { return auth.getToken.value({ template: 'convex', skipCache: false, }) } convex.setAuth(getToken) }) ``` -------------------------------- ### useConvexHttpQuery() Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/auto-imports.md Executes a Convex query over HTTP. Useful for simple data fetching that does not require realtime updates. ```APIDOC ## useConvexHttpQuery(queryFn, args) ### Description Executes a query over HTTP. No realtime updates are provided; the query runs once and the result is cached. ### Parameters - **query** (FunctionReference<"query">) - Required - Reference to a Convex query function from `api`. - **args** (Ref> | Record) - Required - Query arguments; can be a ref for reactivity. ### Return Type - **data** (Ref) - The query result; undefined while loading. - **pending** (Ref) - True while the query is executing. - **error** (Ref) - Error object if query fails, undefined otherwise. ``` -------------------------------- ### Module Defaults Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/implementation-details.md Sets default configuration values for the module. ```typescript defaults: {} ``` -------------------------------- ### Execute Queries with useConvexQuery Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/auto-imports.md Executes reactive Convex queries with support for SSR and automatic updates. ```ts const { data, pending, error } = useConvexQuery(queryFn, args) ``` ```ts function useConvexQuery( query: FunctionReference<"query">, args: Ref> | Record, options?: ComputedRef, ): UseQueryReturn ``` ```ts export default defineComponent({ setup() { const { data: tasks } = useConvexQuery(api.tasks.get, {}) return { tasks } } }) ``` ```ts export default defineComponent({ setup() { const userId = ref('user123') const { data: userTasks } = useConvexQuery( api.tasks.getByUser, () => ({ userId: userId.value }) ) return { userTasks } } }) ``` ```ts export default defineComponent({ setup() { const { data, pending, error } = useConvexQuery(api.tasks.get, {}) return { data, pending, error } } }) ``` ```vue ``` ```vue ``` -------------------------------- ### Fetch data with useConvexQuery Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/README.md Use these patterns to retrieve data from Convex. Supports reactive arguments and error handling. ```ts // Simple query with no arguments const { data: tasks } = useConvexQuery(api.tasks.get, {}) // Query with reactive arguments const userId = ref('user123') const { data: userTasks } = useConvexQuery( api.tasks.getByUser, () => ({ userId: userId.value }) ) // With error handling const { data, pending, error } = useConvexQuery(api.tasks.get, {}) ``` -------------------------------- ### Fetch Data with useConvexQuery Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/getting-started.md Use the useConvexQuery composable to execute realtime queries in your components. ```vue ``` -------------------------------- ### Consume reactive query composable in Vue Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/advanced-topics.md Demonstrates binding input models to the composable and displaying reactive results. ```vue ``` -------------------------------- ### Configure Nuxt for Clerk and Convex Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/advanced-topics.md Add the necessary modules and environment variables to your nuxt.config.ts file. ```typescript export default defineNuxtConfig({ modules: ['@clerk/nuxt', 'convex-nuxt'], clerk: { publishableKey: process.env.NUXT_PUBLIC_CLERK_PUBLISHABLE_KEY, }, convex: { url: process.env.NUXT_CONVEX_URL, }, }) ``` -------------------------------- ### Access Runtime Configuration Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/api-reference/module.md Retrieves the Convex configuration settings at runtime using the Nuxt runtime config. ```ts const config = useRuntimeConfig() const convexOptions = config.public.convex ``` -------------------------------- ### Configure Convex Nuxt Module Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/overview.md Define the Convex URL and other options within the nuxt.config.ts file to initialize the module. ```ts export default defineNuxtConfig({ modules: ['convex-nuxt'], convex: { url: 'https://your-convex-url.convex.dev', // Required // Other convex-vue options... }, }) ``` -------------------------------- ### Module Distribution Structure Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/implementation-details.md The file structure of the compiled module output. ```text dist/ ├── module.mjs # Main module export ├── module.d.mts # Type definitions for module ├── types.d.mts # Exported types ├── runtime/ │ ├── plugin.mjs # Compiled plugin │ └── plugin.d.mts # Plugin types └── ... ``` -------------------------------- ### Configure SSG in nuxt.config.ts Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/getting-started.md Configure the convex-nuxt module and route rules for static site generation. ```ts // nuxt.config.ts export default defineNuxtConfig({ modules: ['convex-nuxt'], convex: { url: process.env.NUXT_CONVEX_URL, }, routeRules: { '/': { swr: 3600 }, // Cache for 1 hour }, }) ``` -------------------------------- ### Plugin Configuration Retrieval Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/implementation-details.md Retrieving the convex configuration from the public runtime config. ```typescript const options = useRuntimeConfig().public.convex // { url: '...' } ``` -------------------------------- ### Create Mutation Composable Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/getting-started.md Encapsulate mutation logic into a reusable composable for managing data updates. ```ts // composables/useTaskMutations.ts export const useTaskMutations = () => { const { mutate: addTask } = useConvexMutation(api.tasks.add) const { mutate: deleteTask } = useConvexMutation(api.tasks.remove) return { addTask, deleteTask, } } ``` -------------------------------- ### Define Nuxt Plugin Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/api-reference/plugin.md Initializes the convex-vue plugin using the public runtime configuration. ```ts export default defineNuxtPlugin((nuxtApp) => { const options = useRuntimeConfig().public.convex nuxtApp.vueApp.use(convexVue, options) }) ``` -------------------------------- ### Environment-Specific Configuration Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/configuration.md Conditional URL assignment based on the NODE_ENV environment variable. ```ts // nuxt.config.ts export default defineNuxtConfig({ modules: ['convex-nuxt'], convex: { url: process.env.NODE_ENV === 'production' ? process.env.NUXT_CONVEX_URL_PROD : process.env.NUXT_CONVEX_URL_DEV, }, }) ``` -------------------------------- ### Execute Convex HTTP Query Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/auto-imports.md Basic usage of useConvexHttpQuery for non-realtime data fetching. ```ts const { data, pending, error } = useConvexHttpQuery(queryFn, args) ``` -------------------------------- ### Configure Auto-Imports Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/nuxt-integration.md Use the addImports utility to register composables so they are automatically available in components. ```ts addImports([ { name: 'useConvexClient', from: 'convex-vue' }, { name: 'useConvexQuery', from: 'convex-vue' }, // ... ]) ``` -------------------------------- ### Access Configuration at Runtime Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/configuration.md Retrieve the Convex URL from the public runtime configuration in components or composables. ```ts // In any component or composable const config = useRuntimeConfig() console.log(config.public.convex.url) // 'https://my-app.convex.dev' ``` -------------------------------- ### ConvexClient.setAuth Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/types.md Configures the authentication token provider for the Convex client instance. ```APIDOC ## setAuth(getToken: () => Promise) ### Description Sets an asynchronous function that returns an authentication token for the Convex backend. This is typically used to provide tokens from an authentication provider like Clerk. ### Parameters - **getToken** (Function) - Required - An async function that returns a Promise resolving to a string token. ### Usage ```ts const client = useConvexClient(); client.setAuth(async () => { return await getTokenFromAuthProvider(); }); ``` ``` -------------------------------- ### useConvexQuery() Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/auto-imports.md Executes a Convex query with reactive state management, supporting automatic updates and SSR via suspense. ```APIDOC ## useConvexQuery() ### Description Executes a Convex query and returns reactive state for the result, loading status, and errors. It updates automatically when dependencies change. ### Signature `function useConvexQuery(query: FunctionReference<"query">, args: Ref> | Record, options?: ComputedRef): UseQueryReturn` ### Parameters - **query** (FunctionReference) - Required - Reference to a Convex query function. - **args** (Ref | Object) - Required - Query arguments, can be reactive. - **options** (ComputedRef) - Optional - Configuration for query behavior. ### Return Value - **data** (Ref) - The query result. - **pending** (Ref) - Loading status. - **error** (Ref) - Error object if the query fails. ### Usage Example ```ts const { data, pending, error } = useConvexQuery(api.tasks.get, {}); ``` ``` -------------------------------- ### UseMutationReturn Interface Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/types.md The UseMutationReturn interface defines the reactive state and execution method returned by the useConvexMutation hook. ```APIDOC ## UseMutationReturn ### Description Reactive state for executing mutations. The `mutate` function is async and must be awaited. Errors are both thrown and stored in the `error` ref. ### Properties - **mutate** ((args: Args) => Promise) - Execute the mutation; throws on error - **pending** (Ref) - True while mutation executes - **error** (Ref) - Error if mutation fails ### Generic Parameters - **T** - The return type of the mutation function - **Args** (Record) - The argument type expected by the mutation ``` -------------------------------- ### Execute Convex Mutation Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/auto-imports.md Basic usage of useConvexMutation to trigger server-side mutations. ```ts const { mutate, pending, error } = useConvexMutation(mutationFn) ``` -------------------------------- ### useConvexMutation() Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/auto-imports.md Executes a Convex mutation (create, update, or delete operation). Returns a mutate function, pending state, and error state. ```APIDOC ## useConvexMutation(mutationFn) ### Description Executes a Convex mutation. The returned `mutate` function is async and throws if the mutation fails. ### Parameters - **mutation** (FunctionReference<"mutation">) - Required - Reference to a Convex mutation function from `api`. ### Return Type - **mutate** ((args: Args) => Promise) - Async function to execute the mutation with arguments. - **pending** (Ref) - True while the mutation is executing. - **error** (Ref) - Error object if mutation fails, undefined otherwise. ``` -------------------------------- ### Configuring authentication tokens Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/advanced-topics.md Set the auth token provider within a Nuxt plugin using the Convex client. ```ts export default defineNuxtPlugin(() => { const convex = useConvexClient() convex.setAuth(async () => { const token = await getToken() console.log('Token:', token ? 'present' : 'missing') return token }) }) ``` -------------------------------- ### Module Meta Configuration Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/implementation-details.md Defines the module identifier and the configuration key used in nuxt.config.ts. ```typescript meta: { name: 'convex-nuxt', // Module identifier for Nuxt internals configKey: 'convex', // Key in nuxt.config for user configuration } ``` -------------------------------- ### Implement SSR with Suspense Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/getting-started.md Use Vue's Suspense component to handle asynchronous data loading during server-side rendering. ```vue ``` -------------------------------- ### Create a reactive query composable Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/advanced-topics.md Uses ref-based arguments to trigger automatic query re-execution when values change. ```ts // composables/useSearchTasks.ts export const useSearchTasks = () => { const searchTerm = ref('') const userId = ref('') const { data: results, pending } = useConvexQuery( api.tasks.search, () => ({ query: searchTerm.value, userId: userId.value, }) ) return { results, pending, searchTerm, userId } } ``` -------------------------------- ### Register Vue plugin in Nuxt Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/types.md Demonstrates accessing the Vue app instance within a Nuxt plugin to register external plugins. ```ts // In src/runtime/plugin.ts export default defineNuxtPlugin((nuxtApp) => { nuxtApp.vueApp.use(convexVue, options) }) ``` -------------------------------- ### Enable Debug Mode Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/advanced-topics.md Configure debug logging in nuxt.config.ts to assist with troubleshooting. ```ts // nuxt.config.ts export default defineNuxtConfig({ modules: ['convex-nuxt'], convex: { url: 'https://...', }, // Enable debug logging runtimeConfig: { public: { debug: true, }, }, }) ``` -------------------------------- ### Ensuring query reactivity Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/advanced-topics.md Pass a function to useConvexQuery to ensure arguments remain reactive. ```ts // ❌ Not reactive const args = { userId: 'user123' } const { data } = useConvexQuery(api.tasks.getByUser, args) // ✅ Reactive function const { data } = useConvexQuery(api.tasks.getByUser, () => ({ userId: userId.value })) ``` -------------------------------- ### Auto-imported Composables Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/api-reference/module.md The module automatically provides several composables for interacting with Convex, available globally in Nuxt components and composables. ```APIDOC ## Auto-imported Composables ### Description The following composables are automatically imported from `convex-vue` and available throughout the Nuxt application without manual imports. ### Composables - **useConvexClient** - Access the underlying Convex client instance for custom operations. - **useConvexQuery** - Execute realtime Convex queries with reactive updates. - **useConvexMutation** - Execute Convex mutations (create, update, delete operations). - **useConvexHttpQuery** - Execute HTTP-based queries as an alternative to realtime queries. ``` -------------------------------- ### Retrieve Runtime Configuration Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/api-reference/plugin.md Accesses the Convex configuration object from the Nuxt public runtime config. ```ts const options = useRuntimeConfig().public.convex ``` -------------------------------- ### Configure Nuxt Lifecycle Hooks Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/nuxt-integration.md Hook into Nuxt's lifecycle within defineNuxtConfig to execute logic once the app is initialized and Convex is available. ```ts export default defineNuxtConfig({ hooks: { 'app:created': () => { // App initialized, Convex available }, }, }) ``` -------------------------------- ### Configure Nuxt Modules Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/nuxt-integration.md Register the convex-nuxt module alongside other common Nuxt modules in the configuration file. ```ts export default defineNuxtConfig({ modules: [ // Auth modules '@clerk/nuxt', // UI frameworks '@nuxt/ui', '@nuxtjs/tailwindcss', // Convex integration 'convex-nuxt', // Other integrations '@nuxtjs/i18n', ], }) ``` -------------------------------- ### Use auto-imported Convex query Source: https://github.com/chris-visser/convex-nuxt/blob/main/_autodocs/00_START_HERE.md Access Convex data using the auto-imported useConvexQuery composable without manual imports. ```vue ```