### Install Convex and React Query Packages Source: https://docs.convex.dev/quickstart/tanstack-start Installs necessary npm packages for Convex client and server, along with React Query integration for TanStack Start. This includes 'convex', '@convex-dev/react-query', '@tanstack/react-router-with-query', and '@tanstack/react-query'. ```bash npm install convex @convex-dev/react-query @tanstack/react-router-with-query @tanstack/react-query ``` -------------------------------- ### Run example project with Git and npm Source: https://docs.convex.dev/agents/files Commands to clone, setup, and run the example project using Git and npm. ```bash git clone https://github.com/get-convex/agent.git cd agent npm run setup npm run example ``` -------------------------------- ### Create TanStack Start App with Convex Source: https://docs.convex.dev/quickstart/tanstack-start Command to initialize a new TanStack Start project with Convex integration. It uses npm to create a Convex project with the 'tanstack-start' template. ```bash npm create convex@latest -- -t tanstack-start ``` -------------------------------- ### Create Nuxt App and Install Convex Source: https://docs.convex.dev/quickstart/nuxt Commands to create a new Nuxt application and install the necessary Convex packages (`convex` and `convex-nuxt`). ```bash npm create nuxt@latest my-nuxt-app cd my-nuxt-app && npm install convex && npx nuxi module add convex-nuxt ``` -------------------------------- ### Install Convex Agent package Source: https://docs.convex.dev/agents/getting-started Installs the Convex Agent package using npm. This is required to use the agent functionality in your Convex project. ```bash npm install @convex-dev/agent ``` -------------------------------- ### Install Convex Client Library Source: https://docs.convex.dev/client/nextjs/pages-router/quickstart Installs the 'convex' npm package, which provides the necessary client-side library for interacting with Convex services from a React application. ```bash cd my-app && npm install convex ``` -------------------------------- ### Install Convex CLI Source: https://docs.convex.dev/using/cli Installs the Convex CLI using npm. This is the first step to start managing your Convex projects. ```bash npm install convex ``` -------------------------------- ### Install Convex Client and Server using npm Source: https://docs.convex.dev/quickstart/android This command installs the Convex client and server libraries using npm in the project's terminal. It initializes a new npm project if one doesn't exist and then installs the 'convex' package. ```bash npm init -y npm install convex ``` -------------------------------- ### Start Next.js Development Server Source: https://docs.convex.dev/client/nextjs/pages-router/quickstart Runs the Next.js development server, making the application accessible at http://localhost:3000 and allowing you to view the integrated Convex data. ```bash npm run dev ``` -------------------------------- ### Clone, Setup, and Run RAG Example (Shell) Source: https://docs.convex.dev/agents/rag These commands clone the RAG repository, set up the project, and run the RAG example to see the implemented features in action. This allows users to explore the complete RAG functionality. ```Shell git clone https://github.com/get-convex/rag.git cd rag npm run setup npm run example ``` -------------------------------- ### Install Convex library in Remix Source: https://docs.convex.dev/quickstart/remix Installs the necessary Convex client library for a Remix project using npm. Ensure you are in the root directory of your Remix application before running this command. ```bash cd my-remix-app && npm install convex ``` -------------------------------- ### Install Convex Libraries Source: https://docs.convex.dev/quickstart/svelte Installs the necessary Convex client and server libraries for SvelteKit integration. This includes the core 'convex' package and the 'convex-svelte' adapter. ```bash cd my-app && npm install convex convex-svelte ``` -------------------------------- ### Install Convex Client and Server Libraries Source: https://docs.convex.dev/quickstart/rust Installs the necessary npm packages for Convex backend development and the Convex Rust client library, along with the Tokio runtime and dotenvy for environment variable management. This command ensures all required dependencies are available for both frontend and backend interactions. ```bash npm init -y && npm install convex && cargo add convex tokio dotenvy ``` -------------------------------- ### Start React Native App Source: https://docs.convex.dev/quickstart/react-native Command to start the React Native development server using npm. This allows you to run the application on a simulator or a physical device. ```bash npm start ``` -------------------------------- ### Configure Convex Agent in convex.config.ts Source: https://docs.convex.dev/agents/getting-started Configures the Convex Agent in the convex.config.ts file. This setup is necessary to integrate the agent into your Convex application. ```typescript // convex/convex.config.ts import { defineApp } from "convex/server"; import agent from "@convex-dev/agent/convex.config"; const app = defineApp(); app.use(agent); export default app; ``` -------------------------------- ### Install Convex and Dotenv Packages Source: https://docs.convex.dev/quickstart/nodejs Installs the necessary npm packages for interacting with Convex and loading environment variables. The 'convex' package provides the client interface, while 'dotenv' helps manage configuration. ```bash npm install convex dotenv ``` -------------------------------- ### Install Convex and Dependencies (npm & pip) Source: https://docs.convex.dev/quickstart/python This command installs the Convex npm package for backend development and the Convex Python client library along with python-dotenv for managing environment variables. It assumes you are in the 'my-app' directory. ```bash cd my-app && npm init -y && npm install convex && venv/bin/pip install convex python-dotenv ``` -------------------------------- ### Install Convex Vue Library Source: https://docs.convex.dev/quickstart/vue Installs the `convex-vue` package into the Vue project, which provides the necessary tools to interact with Convex. ```bash cd my-vue-app && npm install convex-vue ``` -------------------------------- ### Root Route Setup with Clerk and Convex Authentication Source: https://docs.convex.dev/client/tanstack/tanstack-start/clerk Sets up the root route for a TanStack Start application, integrating Clerk authentication and Convex client. It defines server-side fetching for Clerk authentication tokens and configures the `beforeLoad` function to attach these tokens to the Convex client for server-side HTTP requests. ```typescript import { Link, Outlet, createRootRouteWithContext, useRouteContext, } from '@tanstack/react-router' import { ClerkProvider, SignInButton, SignedIn, SignedOut, UserButton, useAuth, } from '@clerk/tanstack-start' import { TanStackRouterDevtools } from '@tanstack/router-devtools' import { Meta, Scripts, createServerFn } from '@tanstack/start' import { QueryClient } from '@tanstack/react-query' import * as React from 'react' import { getAuth } from '@clerk/tanstack-start/server' import { getWebRequest } from 'vinxi/http' import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary.js' import { NotFound } from '~/components/NotFound.js' import appCss from '~/styles/app.css?url' import { ConvexQueryClient } from '@convex-dev/react-query' import { ConvexReactClient } from 'convex/react' import { ConvexProviderWithClerk } from 'convex/react-clerk' const fetchClerkAuth = createServerFn({ method: 'GET' }).handler(async () => { const auth = await getAuth(getWebRequest()) const token = await auth.getToken({ template: 'convex' }) return { userId: auth.userId, token, } }) export const Route = createRootRouteWithContext<{ queryClient: QueryClient convexClient: ConvexReactClient convexQueryClient: ConvexQueryClient }>()({ head: () => ({ meta: [ { charSet: 'utf-8', }, { name: 'viewport', content: 'width=device-width, initial-scale=1', }, ], links: [ { rel: 'stylesheet', href: appCss }, { rel: 'apple-touch-icon', sizes: '180x180', href: '/apple-touch-icon.png', }, { rel: 'icon', type: 'image/png', sizes: '32x32', href: '/favicon-32x32.png', }, { rel: 'icon', type: 'image/png', sizes: '16x16', href: '/favicon-16x16.png', }, { rel: 'manifest', href: '/site.webmanifest', color: '#fffff' }, { rel: 'icon', href: '/favicon.ico' }, ], }), beforeLoad: async (ctx) => { const auth = await fetchClerkAuth() const { userId, token } = auth // During SSR only (the only time serverHttpClient exists), // set the Clerk auth token to make HTTP queries with. if (token) { ctx.context.convexQueryClient.serverHttpClient?.setAuth(token) } ``` -------------------------------- ### Integrate Convex Client in HTML (JavaScript) Source: https://docs.convex.dev/quickstart/script-tag Embeds the Convex client library and initializes a ConvexClient with a provided deployment URL. It then sets up a real-time listener for the `tasks:get` query, logging the task texts to the console upon updates. ```html ``` -------------------------------- ### Create Sample Data for Convex Database Source: https://docs.convex.dev/quickstart/tanstack-start Defines sample data in JSON Lines format for the Convex database. Each line represents a record, with fields like 'text' and 'isCompleted'. This is used for populating the database. ```json {"text": "Buy groceries", "isCompleted": true} {"text": "Go for a swim", "isCompleted": true} {"text": "Integrate Convex", "isCompleted": false} ``` -------------------------------- ### Start Convex Development Server Source: https://docs.convex.dev/cli Starts the Convex development server. This command initializes a new project if one is not found, sets up the development environment, and watches for file changes to push updates automatically. It also displays logs from the development deployment. ```bash npx convex dev ``` -------------------------------- ### Run Rust Application Source: https://docs.convex.dev/quickstart/rust Executes the Rust application after all setup and coding steps are completed. This command compiles and runs the `main.rs` file, triggering the Convex client to fetch and display data. ```bash cargo run ``` -------------------------------- ### Setup Convex with Background Agents using npm Source: https://docs.convex.dev/ai This snippet shows how to set up a Convex deployment for background agents using npm. It installs dependencies and starts Convex in agent mode with anonymous authentication. This is useful for remote development environments like ChatGPT Codex. ```bash npm i CONVEX_AGENT_MODE=anonymous npx convex dev --once ``` -------------------------------- ### Start Convex Dev Deployment Source: https://docs.convex.dev/quickstart/bun Starts a Convex development deployment. This command handles authentication, project creation, saving deployment URLs, and syncing backend API functions. ```bash bunx convex dev ``` -------------------------------- ### Install and Run Convex Locally Source: https://docs.convex.dev/ai/using-cursor These commands demonstrate how to install the Convex package and run the Convex development server. Keeping Convex running locally is essential for automatically generating client-side types, which prevents AI agents from getting stuck in linting loops. ```shell npm install convex npx convex dev ``` -------------------------------- ### Basic usage of Convex Agent to get weather Source: https://docs.convex.dev/agents/getting-started Demonstrates basic usage of the Convex Agent to fetch weather information for a specified city. The action creates a thread and generates text based on the prompt. ```typescript import { action } from "./_generated/server"; import { v } from "convex/values"; export const helloWorld = action({ args: { city: v.string() }, handler: async (ctx, { city }) => { const threadId = await createThread(ctx, components.agent); const prompt = `What is the weather in ${city}?`; const result = await agent.generateText(ctx, { threadId }, { prompt }); return result.text; }, }); ``` -------------------------------- ### Configure Convex and React Query Router Source: https://docs.convex.dev/quickstart/tanstack-start Replaces `app/router.tsx` to set up the Convex client and QueryClient, integrating them with the TanStack Router. It initializes `ConvexQueryClient`, configures `QueryClient` with Convex query functions, and wraps the router with `ConvexProvider`. ```typescript import { createRouter } from "@tanstack/react-router"; import { QueryClient } from "@tanstack/react-query"; import { routerWithQueryClient } from "@tanstack/react-router-with-query"; import { ConvexQueryClient } from "@convex-dev/react-query"; import { ConvexProvider } from "convex/react"; import { routeTree } from "./routeTree.gen"; export function getRouter() { const CONVEX_URL = (import.meta as any).env.VITE_CONVEX_URL!; if (!CONVEX_URL) { console.error("missing envar VITE_CONVEX_URL"); } const convexQueryClient = new ConvexQueryClient(CONVEX_URL); const queryClient: QueryClient = new QueryClient({ defaultOptions: { queries: { queryKeyHashFn: convexQueryClient.hashFn(), queryFn: convexQueryClient.queryFn(), }, }, }); convexQueryClient.connect(queryClient); const router = routerWithQueryClient( createRouter({ routeTree, defaultPreload: "intent", context: { queryClient }, scrollRestoration: true, Wrap: ({ children }) => ( {children} ), }), queryClient, ); return router; } ``` -------------------------------- ### Reset Expo Project Source: https://docs.convex.dev/quickstart/react-native Command to reset the Expo project's app directory to its initial state. This is useful for starting with a clean project setup. ```bash npm run reset-project ``` -------------------------------- ### Create SvelteKit App Source: https://docs.convex.dev/quickstart/svelte Initializes a new SvelteKit project with specific configurations for a minimal TypeScript setup. This command is the first step in integrating Convex with a Svelte application. ```bash npx sv@latest create my-app ``` -------------------------------- ### Create Next.js App with npm Source: https://docs.convex.dev/quickstart/nextjs Initializes a new Next.js application using npm. This command sets up the basic structure for a Next.js project. ```bash npm create convex@latest ``` -------------------------------- ### Install Convex CLI Source: https://docs.convex.dev/cli Installs the Convex CLI using npm. This is the first step to using the Convex command-line tools. ```bash npm install convex ``` -------------------------------- ### Define Convex Query Function Source: https://docs.convex.dev/quickstart/tanstack-start Example of a Convex backend query function defined in `convex/tasks.ts`. Exporting a function like this makes it available via `api.tasks.get`, allowing client-side access to load data from the 'tasks' table. ```typescript import { query } from "convex/server"; export const get = query({ args: {}, handler: async (ctx) => { return await ctx.db.query("tasks").collect(); }, }); ``` -------------------------------- ### React: ConvexProviderWithClerk Setup Source: https://docs.convex.dev/client/tanstack/tanstack-start/clerk This snippet shows the root component setup for a React application using Convex and Clerk. It wraps the main application content with ConvexProviderWithClerk, passing the Convex client and a custom useAuth hook. It also includes TanStack Router's Outlet for rendering nested routes and TanStack Query Devtools for debugging. ```jsx function RootComponent() { const context = useRouteContext({ from: Route.id }) return ( ) } ``` -------------------------------- ### Start Convex Development Server Source: https://docs.convex.dev/using/cli Initializes a new Convex project or configures an existing one. It creates the `convex/` directory and `.env.local` file. This command also watches for file changes and pushes updates to your dev deployment. ```bash npx convex dev ``` ```bash npx convex dev --tail-logs always ``` ```bash npx convex dev --tail-logs disable ``` -------------------------------- ### Start Convex MCP Server Source: https://docs.convex.dev/ai/convex-mcp-server Command to start the Convex MCP server using npx. This is the primary command for setting up the server to enable AI agent interaction with your Convex deployment. ```bash npx -y convex@latest mcp start ``` -------------------------------- ### Import Sample Data into Convex Source: https://docs.convex.dev/client/nextjs/pages-router/quickstart Imports the sample data from 'sampleData.jsonl' into a new 'tasks' table within the Convex database using the Convex CLI. ```bash npx convex import --table tasks sampleData.jsonl ``` -------------------------------- ### TanStack Router Setup with Convex Client Source: https://docs.convex.dev/client/tanstack/tanstack-start/clerk Configures the TanStack router with Convex integration. It initializes the Convex client and query client, setting up query options to use Convex's hashing and query functions. The ConvexProvider is wrapped around the router's children to ensure Convex context is available. ```typescript import { createRouter as createTanStackRouter } from '@tanstack/react-router' import { routeTree } from './routeTree.gen' import { DefaultCatchBoundary } from './components/DefaultCatchBoundary' import { NotFound } from './components/NotFound' import { routerWithQueryClient } from '@tanstack/react-router-with-query' import { ConvexProvider, ConvexReactClient } from 'convex/react' import { ConvexQueryClient } from '@convex-dev/react-query' import { QueryClient } from '@tanstack/react-query' export function createRouter() { const CONVEX_URL = (import.meta as any).env.VITE_CONVEX_URL! if (!CONVEX_URL) { throw new Error('missing VITE_CONVEX_URL envar') } const convex = new ConvexReactClient(CONVEX_URL, { unsavedChangesWarning: false, }) const convexQueryClient = new ConvexQueryClient(convex) const queryClient: QueryClient = new QueryClient({ defaultOptions: { queries: { queryKeyHashFn: convexQueryClient.hashFn(), queryFn: convexQueryClient.queryFn(), }, }, }) convexQueryClient.connect(queryClient) const router = routerWithQueryClient( createTanStackRouter({ routeTree, defaultPreload: 'intent', defaultErrorComponent: DefaultCatchBoundary, defaultNotFoundComponent: () => , context: { queryClient, convexClient: convex, convexQueryClient }, scrollRestoration: true, Wrap: ({ children }) => ( {children} ), }), queryClient, ) return router } declare module '@tanstack/react-router' { interface Register { router: ReturnType } } ``` -------------------------------- ### Configure Root Route for React Query Context Source: https://docs.convex.dev/quickstart/tanstack-start Updates the `app/routes/__root.tsx` file in a TanStack Start application to include a `QueryClient` in the router context. This makes React Query accessible throughout the application. It sets up basic meta tags and the root component structure. ```typescript import { QueryClient } from "@tanstack/react-query"; import { createRootRouteWithContext } from "@tanstack/react-router"; import { Outlet, Scripts, HeadContent } from "@tanstack/react-router"; import * as React from "react"; export const Route = createRootRouteWithContext<{ queryClient: QueryClient }>()({ head: () => ({ meta: [ { charSet: "utf-8", }, { name: "viewport", content: "width=device-width, initial-scale=1", }, { title: "TanStack Start Starter", }, ], }), component: RootComponent, }); function RootComponent() { return ( ); } function RootDocument({ children }: { children: React.ReactNode }) { return ( {children} ); } ``` -------------------------------- ### Python Client to Fetch Convex Data Source: https://docs.convex.dev/quickstart/python A Python script that uses the ConvexClient to connect to your Convex deployment URL (loaded from environment variables). It fetches data using the 'tasks:get' query and subscribes to real-time updates. ```python import os from convex import ConvexClient from dotenv import load_dotenv load_dotenv(".env.local") CONVEX_URL = os.getenv("CONVEX_URL") # or you can hardcode your deployment URL instead # CONVEX_URL = "https://happy-otter-123.convex.cloud" client = ConvexClient(CONVEX_URL) print(client.query("tasks:get")) for tasks in client.subscribe("tasks:get"): print(tasks) # this loop lasts forever, ctrl-c to exit it ``` -------------------------------- ### Connect to Convex and Execute Query (Node.js) Source: https://docs.convex.dev/quickstart/nodejs Creates a Convex HTTP client, loads environment variables, and executes the 'api.tasks.get' query. The results are then logged to the console. ```javascript import { ConvexHttpClient } from "convex/browser"; import { api } from "./convex/_generated/api.js"; import * as dotenv from "dotenv"; dotenv.config({ path: ".env.local" }); const client = new ConvexHttpClient(process.env["CONVEX_URL"]); client.query(api.tasks.get).then(console.log); ``` -------------------------------- ### Install Convex Helpers CLI Source: https://docs.convex.dev/client/open-api Installs the `convex-helpers` npm package, which includes a command-line interface for generating OpenAPI specifications from a Convex deployment. ```bash npm install convex-helpers ``` -------------------------------- ### Define Sample Data for Convex Database Source: https://docs.convex.dev/client/nextjs/pages-router/quickstart Creates a JSON Lines file containing sample task data. This data will be imported into the Convex database to populate the 'tasks' table. ```json {"text": "Buy groceries", "isCompleted": true} {"text": "Go for a swim", "isCompleted": true} {"text": "Integrate Convex", "isCompleted": false} ``` -------------------------------- ### Setup Convex with Background Agents using bun Source: https://docs.convex.dev/ai This snippet demonstrates setting up a Convex deployment for background agents using bun. It installs dependencies via bun and then executes Convex in agent mode with anonymous authentication. This is an alternative for environments using the bun package manager. ```bash bun i CONVEX_AGENT_MODE=anonymous bun x convex dev --once ``` -------------------------------- ### Connect Rust App to Convex Backend and Query Data Source: https://docs.convex.dev/quickstart/rust Initializes a Convex client in a Rust application, loads environment variables, and makes a query to the `tasks:get` API endpoint. The result of the query, a serialized list of tasks, is then printed to the console. ```rust use std::{ collections::BTreeMap, env, }; use convex::ConvexClient; #[tokio::main] async fn main() { dotenvy::from_filename(".env.local").ok(); dotenvy::dotenv().ok(); let deployment_url = env::var("CONVEX_URL").unwrap(); let mut client = ConvexClient::new(&deployment_url).await.unwrap(); let result = client.query("tasks:get", BTreeMap::new()).await.unwrap(); println!("{result:#?}"); } ``` -------------------------------- ### Setup ESLint 9 (Flat Config) with Convex Plugin Source: https://docs.convex.dev/eslint Installs the Convex ESLint plugin and configures ESLint 9's flat config (`eslint.config.js`) to include recommended Convex rules. Assumes npm is used for installation. ```bash npm i @convex-dev/eslint-plugin --save-dev ``` ```javascript import convexPlugin from "@convex-dev/eslint-plugin"; import { defineConfig } from "eslint/config"; export default defineConfig([ // Other configurations ...convexPlugin.configs.recommended, ]); ``` -------------------------------- ### Install Project Dependencies with npm Source: https://docs.convex.dev/chef This command uses npm (Node Package Manager) to install all the necessary dependencies for your project. Ensure you have Node.js and npm installed. ```bash npm i ``` -------------------------------- ### Setup Convex Client in SvelteKit Layout (TypeScript) Source: https://docs.convex.dev/quickstart/svelte Configures the Convex client within the SvelteKit application's layout component. This makes the Convex client available across all pages by setting up the connection using the public Convex URL. ```typescript {@render children()} ``` -------------------------------- ### Install Clerk Next.js SDK Source: https://docs.convex.dev/auth/clerk This command installs the Clerk Next.js SDK, which is necessary for integrating Clerk's authentication features into a Next.js application. ```bash npm install @clerk/nextjs ``` -------------------------------- ### Create Vue Site with npm Source: https://docs.convex.dev/quickstart/vue Command to create a new Vue project using npm. It prompts the user to select TypeScript and other configurations. ```bash npm create vue@latest my-vue-app ``` -------------------------------- ### Define a Convex Agent with weather forecasting Source: https://docs.convex.dev/agents/getting-started Defines a new Convex Agent with weather forecasting capabilities. The agent uses GPT-4 for language processing and has tools for weather and geocoding. ```typescript import { components } from "./_generated/api"; import { Agent } from "@convex-dev/agent"; import { openai } from "@ai-sdk/openai"; const agent = new Agent(components.agent, { name: "My Agent", languageModel: openai.chat("gpt-4o-mini"), instructions: "You are a weather forecaster.", tools: { getWeather, getGeocoding }, maxSteps: 3, }); ``` -------------------------------- ### Expose Database Query in Convex (JavaScript) Source: https://docs.convex.dev/client/nextjs/pages-router/quickstart Defines a Convex server-side query function named 'get' in 'convex/tasks.js'. This function queries the 'tasks' table and returns all entries. It's accessible via `api.tasks.get`. ```javascript import { query } from "./_generated/server"; export const get = query({ args: {}, handler: async (ctx) => { return await ctx.db.query("tasks").collect(); }, }); ``` -------------------------------- ### Install Convex Client and Server Library Source: https://docs.convex.dev/quickstart/bun Installs the 'convex' package, which includes the client and server libraries necessary for integrating Convex into your Bun project. ```bash bun add convex ``` -------------------------------- ### Initialize React App with Vite and TypeScript Source: https://docs.convex.dev/quickstart/react Creates a new React application using Vite with a TypeScript template. This is the initial step to set up the project structure. ```bash npm create vite@latest my-app -- --template react-ts ``` -------------------------------- ### Create Next.js App with Pages Router Source: https://docs.convex.dev/client/nextjs/pages-router/quickstart Initializes a new Next.js application using the Pages Router and JavaScript. This command ensures the correct project structure for integration with Convex. ```bash npx create-next-app@latest my-app --no-app --js ``` -------------------------------- ### Start a Local Convex Development Deployment Source: https://docs.convex.dev/cli/local-deployments This command starts a local Convex deployment for development. The local backend runs as a subprocess and exits when the command stops. State is stored in `~/.convex/`. ```bash npx convex dev --local --once ``` -------------------------------- ### Install AuthKit Dependencies Source: https://docs.convex.dev/auth/authkit Installs required packages for AuthKit and Convex integration. Includes React SDK for AuthKit and WorkOS Convex adapter. ```Shell npm install @workos-inc/authkit-react @convex-dev/workos ``` -------------------------------- ### Install Convex npm Package Source: https://docs.convex.dev/understanding/workflow Installs the Convex npm package as a dependency for your project. This is the first step in integrating Convex into your application. ```bash npm i convex ``` -------------------------------- ### Install Clerk React SDK Source: https://docs.convex.dev/auth/clerk A command to install the Clerk React SDK using npm, which is necessary for integrating Clerk's authentication components and hooks into a React application. ```bash npm install @clerk/clerk-react ``` -------------------------------- ### Initialize Convex Client in Android Kotlin Source: https://docs.convex.dev/quickstart/android Initializes the Convex client for Android applications using Kotlin. This setup is essential for connecting to your Convex backend and enabling real-time data synchronization. It requires the ConvexClient library. ```kotlin import dev.convex.android.ConvexClient // Assume convexClient is initialized elsewhere, for example: // val convexClient = ConvexClient(deploymentUrl = "YOUR_DEPLOYMENT_URL") ``` -------------------------------- ### Setup Convex with TanStack Query in React Source: https://docs.convex.dev/client/tanstack/tanstack-query Provides instructions and code for setting up the TanStack Query adapter for Convex in a React application. This involves installing the `@convex-dev/react-query` library and configuring both Convex and TanStack Query clients within the application's entry point (`src/main.tsx`). It ensures that both `ConvexProvider` and `QueryClientProvider` wrap the application to enable the use of hooks from both libraries. ```bash npm i @convex-dev/react-query ``` ```typescript import { ConvexQueryClient } from "@convex-dev/react-query"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { ConvexProvider, ConvexReactClient } from "convex/react"; import ReactDOM from "react-dom/client"; import App from "./App"; import "./index.css"; const convex = new ConvexReactClient(import.meta.env.VITE_CONVEX_URL); const convexQueryClient = new ConvexQueryClient(convex); const queryClient = new QueryClient({ defaultOptions: { queries: { queryKeyHashFn: convexQueryClient.hashFn(), queryFn: convexQueryClient.queryFn(), }, }, }); convexQueryClient.connect(queryClient); ReactDOM.createRoot(document.getElementById("root")!).render( , ); ``` -------------------------------- ### Install Convex Test and Vitest Dependencies Source: https://docs.convex.dev/testing/convex-test This command installs the necessary development dependencies for testing Convex functions using Vitest and the convex-test library. It includes the edge-runtime VM for compatibility. ```bash npm install --save-dev convex-test vitest @edge-runtime/vm ``` -------------------------------- ### Connect Next.js App to Convex (JavaScript) Source: https://docs.convex.dev/client/nextjs/pages-router/quickstart Sets up the Convex client and provider in the Next.js application's entry point ('pages/_app.js'). It initializes `ConvexReactClient` with the Convex URL from environment variables and wraps the application with `ConvexProvider`. ```javascript import "@/styles/globals.css"; import { ConvexProvider, ConvexReactClient } from "convex/react"; const convex = new ConvexReactClient(process.env.NEXT_PUBLIC_CONVEX_URL); export default function App({ Component, pageProps }) { return ( ); } ``` -------------------------------- ### Install Convex Helpers CLI Source: https://docs.convex.dev/production/multiple-repos Installs the `convex-helpers` npm package, which provides a CLI command for generating TypeScript API files for Convex deployments. This is the first step in enabling type-safe client calls from separate repositories. ```bash npm install convex-helpers ``` -------------------------------- ### Install AuthKit Next.js SDK and Convex WorkOS Package Source: https://docs.convex.dev/auth/authkit Installs the necessary npm packages for integrating AuthKit with a Next.js application and the Convex WorkOS SDK. This command should be run in the project's root directory. ```bash npm install @workos-inc/authkit-nextjs @convex-dev/workos ``` -------------------------------- ### Create and Navigate Cargo Project Source: https://docs.convex.dev/quickstart/rust Initializes a new Rust project using Cargo and changes the directory into the newly created project folder. This is the foundational step for any Rust application. ```bash cargo new my_app cd my_app ``` -------------------------------- ### Open Convex Documentation Source: https://docs.convex.dev/cli Opens the Convex documentation in the default web browser. This command is a quick way to access help and guides. ```bash npx convex docs ``` -------------------------------- ### Initialize ConvexReactClient and Provide to App Source: https://docs.convex.dev/client/react Initializes the `ConvexReactClient` with the backend deployment URL and makes it available to the React component tree using `ConvexProvider`. This setup is essential for enabling interaction with the Convex backend. ```javascript import { ConvexProvider, ConvexReactClient } from "convex/react"; import * as reactDOMRoot from 'react-dom/client'; const convex = new ConvexReactClient("https://.convex.cloud"); reactDOMRoot.render( ); ``` -------------------------------- ### Initialize Git Repository Source: https://docs.convex.dev/chef These commands initialize a Git repository in your project directory, add all existing files to the staging area, and create an initial commit. A .gitignore file is included with the downloaded code. ```bash git init git add --all git commit -m "Initial commit" ``` -------------------------------- ### Run Node.js Script to Fetch Data Source: https://docs.convex.dev/quickstart/nodejs Executes the 'script.js' file using Node.js to fetch and display data from the Convex database. This is the final step to verify the integration. ```bash node script.js ``` -------------------------------- ### Fetch and Subscribe to Data in SwiftUI (Swift) Source: https://docs.convex.dev/quickstart/swift Implements a SwiftUI `View` that fetches and subscribes to real-time updates for todo items from the Convex backend. It uses the `convex.subscribe` method to listen for changes to the 'tasks:get' query and updates the UI accordingly. ```swift struct ContentView: View { @State private var todos: [Todo] = [] var body: some View { List { ForEach(todos, id: \._id) { todo in Text(todo.text) } }.task { for await todos: [Todo] in convex.subscribe(to: "tasks:get") .replaceError(with: []).values { self.todos = todos } }.padding() } } ``` -------------------------------- ### Initialize Node.js Project and Set Type to Module Source: https://docs.convex.dev/quickstart/nodejs Creates a new npm project and configures it to use ES modules. This is a prerequisite for using modern JavaScript syntax and importing Convex client libraries. ```bash mkdir my-project && cd my-project && npm init -y && npm pkg set type="module" ``` -------------------------------- ### Managing Environment Variables with Convex CLI Source: https://docs.convex.dev/production/environment-variables The Convex CLI allows listing and setting environment variables for deployments. Requires npx and Convex CLI installed; commands interact with the current deployment. Lists vars to console; sets key-value pairs, with values up to 8KB and keys up to 40 chars starting with letter. ```bash npx convex env list npx convex env set API_KEY secret-api-key ``` -------------------------------- ### Convex Action in Default JS Environment with Fetch (TypeScript) Source: https://docs.convex.dev/functions/actions An example of a Convex action running in the default JavaScript environment, demonstrating the use of the `fetch` API to call a third-party service. Actions in this environment are faster due to no cold starts and can coexist with other Convex functions in the same file. Note that not all NPM packages are supported. ```typescript import { action } from "./_generated/server"; export const doSomething = action({ args: {}, handler: async () => { const data = await fetch("https://api.thirdpartyservice.com"); // do something with data }, }); ``` -------------------------------- ### Create Python Virtual Environment Source: https://docs.convex.dev/quickstart/python This command creates a new virtual environment for your Python project named 'my-app/venv'. Virtual environments isolate project dependencies. ```bash python3 -m venv my-app/venv ``` -------------------------------- ### React Client Component with TanStack Router and Convex Query Source: https://docs.convex.dev/quickstart/tanstack-start A React component using TanStack Router to display a list of tasks fetched from a Convex backend. It utilizes the `useSuspenseQuery` hook from React Query to asynchronously fetch and manage the query results from `api.tasks.get`. The component maps over the fetched data to render each task's text. ```typescript import { convexQuery } from "@convex-dev/react-query"; import { useSuspenseQuery } from "@tanstack/react-query"; import { createFileRoute } from "@tanstack/react-router"; import { api } from "../../convex/_generated/api"; export const Route = createFileRoute("/")({ component: Home, }); function Home() { const { data } = useSuspenseQuery(convexQuery(api.tasks.get, {{}})); return (
{data.map(({ _id, text }) => (
{text}
))}
); } ``` -------------------------------- ### Deploy Application to Convex Production Source: https://docs.convex.dev/understanding/workflow This command pushes your code to your project's production deployment on Convex. If it's the first time running this command for a project, it will automatically provision the production deployment environment. ```bash npx convex deploy ``` -------------------------------- ### Create React Native App Source: https://docs.convex.dev/quickstart/react-native Command to create a new React Native application using Expo CLI. This sets up the basic project structure for a React Native app. ```bash npx create-expo-app my-app ``` -------------------------------- ### Run Python Main Script Source: https://docs.convex.dev/quickstart/python Executes the Python script named 'main.py' using the Python interpreter from the virtual environment. This will fetch and display data from your Convex database. ```bash venv/bin/python -m main ``` -------------------------------- ### Server-Side Rendering with useSuspenseQuery Source: https://docs.convex.dev/client/tanstack/tanstack-start Demonstrates server-side rendering of Convex queries using `useSuspenseQuery` from React Query in TanStack Start. This ensures consistent data views during SSR and client-side navigation. ```typescript const { data } = useSuspenseQuery(convexQuery(api.messages.list, {})); ``` -------------------------------- ### Calling Queries from Clients (React Example) Source: https://docs.convex.dev/understanding/convex-fundamentals/functions This endpoint demonstrates how to call a query from a React component using the `useQuery` hook and the generated `api` object. ```APIDOC ## React Client Query Call ### Description Shows how to call a query from a React component using the `useQuery` hook. ### Method N/A (React component usage) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example { "a": 1, "b": 2 } ### Response #### Success Response (200) - **data** (any) - The result of the query. #### Response Example { "data": 3 } ``` -------------------------------- ### Install Sharded Counter Component Source: https://docs.convex.dev/components/using-components Installs the Sharded Counter component from npm. This is the first step in integrating a new component into your Convex application. ```bash npm i @convex-dev/sharded-counter ``` -------------------------------- ### Example: Rate Limiter Component Usage Source: https://docs.convex.dev/components/using-components Demonstrates how to use the `limit` API of the Rate Limiter component, with an option to throw an error if the rate limit is hit. This example highlights transaction rollback behavior. ```typescript // Automatically throw an error if the rate limit is hit. await rateLimiter.limit(ctx, "failedLogins", { key: userId, throws: true }); ``` -------------------------------- ### Example .env.local File for Frontend Environment Variables Source: https://docs.convex.dev/client/react/deployment-urls This example .env.local file illustrates how to set frontend-accessible environment variables, including the Convex deployment URL (NEXT_PUBLIC_CONVEX_URL) and other service keys like Sentry DSN and LaunchDarkly SDK ID. These variables are typically used by bundlers to inject values into the client-side code. ```dotenv NEXT_PUBLIC_CONVEX_URL=https://guiltless-dog-960.convex.cloud # examples of other environment variables that might be passed to the frontend NEXT_PUBLIC_SENTRY_DSN=https://123abc@o123.ingest.sentry.io/1234 NEXT_PUBLIC_LAUNCHDARKLY_SDK_CLIENT_SIDE_ID=01234567890abcdef ``` -------------------------------- ### Push Config Audit Log JSON Example Source: https://docs.convex.dev/production/integrations/log-streams/legacy-event-schema This example demonstrates the JSON structure of an audit log entry for the 'push_config' action, including fields for topic, timestamp, action, and actionMetadata with added/removed modules. It is output from Convex's auditing system and serves as a reference for log parsing; actual entries may differ based on deployment details. ```json { "_topic": "_audit_log", "_timestamp": 1695066350531, "action": "push_config", "actionMetadata": { "modules": { "added": ["ffmpeg.js", "fetch.js", "test.js"], "removed": ["removed.js"] } } } ``` -------------------------------- ### Loader for Preloading Data in TanStack Start Source: https://docs.convex.dev/client/tanstack/tanstack-start Illustrates how to use loaders in TanStack Start to preload data for a route using React Query's `ensureQueryData`. This improves client-side navigation performance by fetching data proactively. ```typescript export const Route = createFileRoute('/posts')({ loader: async (opts) => { await opts.context.queryClient.ensureQueryData( convexQuery(api.messages.list, {}), ); }; component: () => { const { data } = useSuspenseQuery(convexQuery(api.messages.list, {})); return (
{data.map((message) => ( ))}
); }, }) ``` -------------------------------- ### Configure Development Clerk Publishable Key (dotenv) Source: https://docs.convex.dev/auth/clerk Example of setting the development Clerk Publishable Key in a `.env.local` file. This key is used for client-side authentication during development. ```dotenv VITE_CLERK_PUBLISHABLE_KEY="pk_test_..." ``` -------------------------------- ### Initialize Convex Client (Swift) Source: https://docs.convex.dev/quickstart/swift Initializes the `ConvexClient` instance in Swift using the deployment URL obtained from the environment. This client is used to establish a connection to the Convex backend and interact with its services. ```swift import SwiftUI import ConvexMobile let convex = ConvexClient(deploymentUrl: "YOUR_CONVEX_URL") ``` -------------------------------- ### Setup Deprecated ESLint (.eslintrc.js) with Convex Plugin Source: https://docs.convex.dev/eslint Installs necessary ESLint plugins and configures the deprecated `.eslintrc.js` format to include recommended TypeScript and Convex rules. Assumes npm is used for installation. ```bash npm i @typescript-eslint/eslint-plugin @convex-dev/eslint-plugin --save-dev ``` ```javascript module.exports = extends: [ // Other configurations "plugin:@typescript-eslint/recommended", "plugin:@convex-dev/recommended", ], ignorePatterns: ["node_modules/", "dist/", "build/"], }; ``` -------------------------------- ### GET Task Source: https://docs.convex.dev/understanding/convex-fundamentals/functions This endpoint demonstrates fetching a task from the database using the `db.get()` method. It shows how to use the query context (`ctx`) and arguments to retrieve data. ```APIDOC ## GET /api/tasks/:id ### Description This endpoint retrieves a task from the database based on its ID. ### Method GET ### Endpoint /api/tasks/:id ### Parameters #### Path Parameters - **id** (id) - Required - The ID of the task to retrieve. #### Query Parameters None #### Request Body None ### Request Example { "id": "task123" } ### Response #### Success Response (200) - **task** (object) - The retrieved task object. #### Response Example { "task": { "id": "task123", "name": "Example Task", "authorId": "user456" } } ``` -------------------------------- ### Show example execution record log event JSON Source: https://docs.convex.dev/production/integrations/log-streams/legacy-event-schema This snippet provides a JSON example of a function execution record log, illustrating fields such as status, reason, and execution timing. It captures both success and failure details for functions, including HTTP actions. Reference this when handling execution record logs in monitoring or analytics pipelines. ```json { "_topic": "_execution_record", "_timestamp": 1695066350531, "_functionType": "httpAction", "_functionPath": "POST /sendImage", "status": "failure", "reason": "Unexpected Error: Some error message\n\n at ....", "executionTimeMs": 73 } ``` -------------------------------- ### GET / Source: https://docs.convex.dev/functions/http-actions Simple hello world HTTP action that returns a greeting message with the request URL. This is the root endpoint for the HTTP API. ```APIDOC ## GET / ### Description Simple hello world HTTP action that returns a greeting message with the request URL. This is the root endpoint for the HTTP API. ### Method GET ### Endpoint / ### Response #### Success Response (200) - **message** (string) - A greeting message containing the request URL #### Response Example ``` Hello from https://your-deployment.convex.site/ ``` ``` -------------------------------- ### Configure Production Clerk Publishable Key (dotenv) Source: https://docs.convex.dev/auth/clerk Example of setting the production Clerk Publishable Key in a `.env` file. This key is used for client-side authentication in the production environment. ```dotenv NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY="pk_live_..." ``` -------------------------------- ### Configure ConvexProvider in Vue Main Entry Point Source: https://docs.convex.dev/quickstart/vue Sets up the Convex client in `src/main.ts` using the `convexVue` plugin. It configures the Convex client URL from environment variables, making it available throughout the Vue application. ```typescript import { convexVue } from 'convex-vue' import { createApp } from 'vue' import App from './App.vue' const app = createApp(App) app.use(convexVue, { url: import.meta.env.VITE_CONVEX_URL, }) app.mount('#app') ``` -------------------------------- ### GET /api/v1/list_environment_variables Source: https://docs.convex.dev/deployment-platform-api Lists environment variables for a deployment. Use a deployment key, team access token, or OAuth application token prefixed with 'Convex '. ```APIDOC ## GET /api/v1/list_environment_variables ### Description Lists environment variables for a Convex deployment. ### Method GET ### Endpoint /api/v1/list_environment_variables ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example {} ### Response #### Success Response (200) - **variables** (array) - Array of environment variable objects. - **variables[].name** (string) - Name of the environment variable. - **variables[].value** (string) - Value of the environment variable. #### Response Example { "variables": [ { "name": "FEATURE_FLAG_NEW_UI", "value": "true" }, { "name": "API_BASE_URL", "value": "https://api.example.com" } ] } ### Error Handling - 401 Unauthorized: Missing or invalid Authorization header. - 403 Forbidden: Key lacks admin access to the deployment. - 404 Not Found: Unknown deployment. - 429 Too Many Requests: Rate limit exceeded. - 500 Internal Server Error: Unexpected server error. ``` -------------------------------- ### Define Playground API Endpoint Configuration Source: https://docs.convex.dev/agents/playground TypeScript code showing how to configure the Playground API by importing components and agents, then using definePlaygroundAPI to expose the necessary endpoints for frontend access. ```typescript import { definePlaygroundAPI } from "@convex-dev/agent"; import { components } from "./_generated/api"; import { weatherAgent, fashionAgent } from "./example"; /** * Here we expose the API so the frontend can access it. * Authorization is handled by passing up an apiKey that can be generated * on the dashboard or via CLI via: * npx convex run --component agent apiKeys:issue */ export const { isApiKeyValid, listAgents, listUsers, listThreads, listMessages, createThread, generateText, fetchPromptContext, } = definePlaygroundAPI(components.agent, { agents: [weatherAgent, fashionAgent], }); ``` -------------------------------- ### Generate API Keys and Run Local Development Server Source: https://docs.convex.dev/agents/playground Shell commands for generating API keys for authentication and running the Playground UI locally using the development server. Includes instructions for issuing multiple keys and server startup. ```shell npx convex run --component agent apiKeys:issue '{name:"..."}' ``` ```shell npx @convex-dev/agent-playground ```