================ CODE SNIPPETS ================ TITLE: Install Convex and React Query Packages DESCRIPTION: Installs the Convex client and server library along with React Query-related packages required for integration with TanStack Start. SOURCE: https://docs.convex.dev/quickstart/tanstack-start LANGUAGE: bash CODE: ``` npm install convex @convex-dev/react-query @tanstack/react-router-with-query @tanstack/react-query ``` -------------------------------- TITLE: Install Agent Component DESCRIPTION: Installs the Convex Agent component package using npm. This is the first step to integrating agent functionality into your Convex project. SOURCE: https://docs.convex.dev/agents/getting-started LANGUAGE: bash CODE: ``` npm install @convex-dev/agent ``` -------------------------------- TITLE: Install Convex Library DESCRIPTION: Installs the Convex package into an existing Remix project. SOURCE: https://docs.convex.dev/quickstart/remix LANGUAGE: bash CODE: ``` cd my-remix-app && npm install convex ``` -------------------------------- TITLE: Start Development Server DESCRIPTION: Starts the development server for the application. This command is typically run using npm. SOURCE: https://docs.convex.dev/quickstart/tanstack-start LANGUAGE: bash CODE: ``` npm run dev ``` -------------------------------- TITLE: Install Convex Client Library DESCRIPTION: Installs the Convex package within the React application directory. SOURCE: https://docs.convex.dev/quickstart/react LANGUAGE: bash CODE: ``` cd my-app && npm install convex ``` -------------------------------- TITLE: Start Next.js Development Server DESCRIPTION: Starts the Next.js development server, allowing you to view the application locally in a browser, typically at http://localhost:3000. SOURCE: https://docs.convex.dev/quickstart/nextjs LANGUAGE: bash CODE: ``` npm run dev ``` -------------------------------- TITLE: Install Convex Client Library DESCRIPTION: Installs the Convex client library for React applications. This package provides the necessary tools to interact with your Convex backend. SOURCE: https://docs.convex.dev/client/react/nextjs-pages-router/quickstart LANGUAGE: bash CODE: ``` cd my-app && npm install convex ``` -------------------------------- TITLE: Start React Development Server DESCRIPTION: Starts the React development server, allowing you to view the application locally in a web browser. The default address is typically http://localhost:3000. SOURCE: https://docs.convex.dev/client/react/quickstart-create-react-app LANGUAGE: bash CODE: ``` npm start ``` -------------------------------- TITLE: Install Convex Client and Libraries DESCRIPTION: Installs the necessary npm package for the Convex backend and the Python client library along with 'python-dotenv' for environment variable management. SOURCE: https://docs.convex.dev/quickstart/python LANGUAGE: bash CODE: ``` cd my-app && npm init -y && npm install convex && venv/bin/pip install convex python-dotenv ``` -------------------------------- TITLE: Install Convex Client Library DESCRIPTION: Installs the Convex client and server library into an existing React application. This package provides the necessary tools to interact with Convex services from a React app. SOURCE: https://docs.convex.dev/client/react/quickstart-create-react-app LANGUAGE: bash CODE: ``` cd my-app && npm install convex ``` -------------------------------- TITLE: Install Convex Client and Server with npm DESCRIPTION: Command to install the Convex client and server library using npm. This is a prerequisite for running Convex locally. SOURCE: https://docs.convex.dev/quickstart/android LANGUAGE: bash CODE: ``` npm init -y npm install convex ``` -------------------------------- TITLE: Install Convex CLI DESCRIPTION: Installs the Convex CLI using npm. This is the first step to start managing Convex projects. SOURCE: https://docs.convex.dev/cli LANGUAGE: bash CODE: ``` npm install convex ``` -------------------------------- TITLE: Install Convex Packages DESCRIPTION: Installs the necessary Convex client and server libraries (`convex`, `convex-svelte`) into a SvelteKit project. SOURCE: https://docs.convex.dev/quickstart/svelte LANGUAGE: bash CODE: ``` cd my-app && npm install convex convex-svelte ``` -------------------------------- TITLE: Start Next.js Development Server DESCRIPTION: Starts the Next.js development server, allowing you to view the application locally. The app will typically be available at http://localhost:3000. SOURCE: https://docs.convex.dev/client/react/nextjs-pages-router/quickstart LANGUAGE: bash CODE: ``` npm run dev ``` -------------------------------- TITLE: Install Convex and Nuxt Module DESCRIPTION: Installs the Convex library and the convex-nuxt module into an existing Nuxt application. Ensures the necessary packages are available for integration. SOURCE: https://docs.convex.dev/quickstart/nuxt LANGUAGE: bash CODE: ``` cd my-nuxt-app && npm install convex && npx nuxi module add convex-nuxt ``` -------------------------------- TITLE: Start Convex Dev Deployment DESCRIPTION: Initiates a local Convex development deployment. This command handles authentication, project creation, URL saving, and synchronizes backend functions with the cloud. It also generates a `src/convex/` folder for backend code. SOURCE: https://docs.convex.dev/client/react/quickstart-create-react-app LANGUAGE: bash CODE: ``` npx convex dev ``` -------------------------------- TITLE: Install Convex Client and Dotenv DESCRIPTION: Installs the necessary npm packages for interacting with Convex and loading environment variables. 'convex' provides the client library, and 'dotenv' is used to manage configuration. SOURCE: https://docs.convex.dev/quickstart/nodejs LANGUAGE: bash CODE: ``` npm install convex dotenv ``` -------------------------------- TITLE: Install Convex Library for Vue DESCRIPTION: Installs the necessary Convex library for Vue.js applications. This command should be run after navigating into the newly created Vue project directory. SOURCE: https://docs.convex.dev/quickstart/vue LANGUAGE: bash CODE: ``` cd my-vue-app && npm install convex-vue ``` -------------------------------- TITLE: Create Vue Site DESCRIPTION: Initializes a new Vue.js project using npm. Users are guided to select TypeScript support and decline other optional features for this quickstart. SOURCE: https://docs.convex.dev/quickstart/vue LANGUAGE: bash CODE: ``` npm create vue@latest my-vue-app ``` -------------------------------- TITLE: Basic GET Endpoint Example DESCRIPTION: An example of defining a simple GET endpoint that responds with a greeting. SOURCE: https://docs.convex.dev/functions/http-actions LANGUAGE: APIDOC CODE: ``` ## GET / ### Description Responds with a greeting including the request URL. ### Method GET ### Endpoint / ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **response** (Response) - A Fetch API Response object. #### Response Example ``` Hello from https://.convex.site/ ``` ``` -------------------------------- TITLE: Create a Remix Site DESCRIPTION: Initializes a new Remix project using the create-remix CLI. SOURCE: https://docs.convex.dev/quickstart/remix LANGUAGE: bash CODE: ``` npx create-remix@latest my-remix-app ``` -------------------------------- TITLE: Start React Native Development Server DESCRIPTION: Starts the Expo development server, which allows you to run and preview your React Native application on a simulator or a physical device via a QR code. SOURCE: https://docs.convex.dev/quickstart/react-native LANGUAGE: bash CODE: ``` npm start ``` -------------------------------- TITLE: Create Cargo Project and Install Dependencies DESCRIPTION: Initializes a new Rust project using Cargo and installs necessary libraries including the Convex client, Tokio runtime, and dotenvy for environment variable management. SOURCE: https://docs.convex.dev/quickstart/rust LANGUAGE: shell CODE: ``` cargo new my_app cd my_app npm init -y && npm install convex && cargo add convex tokio dotenvy ``` -------------------------------- TITLE: Run Convex Dev Server DESCRIPTION: This command installs the Convex package and starts the Convex development server. Keeping the Convex server running is crucial for automatically generating client-side types, which helps prevent AI agents from getting stuck in linting loops due to inaccessible types for queries and mutations. SOURCE: https://docs.convex.dev/ai/using-cursor LANGUAGE: bash CODE: ``` npm install convex npx convex dev ``` -------------------------------- TITLE: Run Rust Application DESCRIPTION: Executes the Rust application after all setup and backend integration steps are completed. SOURCE: https://docs.convex.dev/quickstart/rust LANGUAGE: shell CODE: ``` cargo run ``` -------------------------------- TITLE: Install Convex Helpers CLI DESCRIPTION: Installs the `convex-helpers` npm package, which includes a CLI command for generating OpenAPI specifications from a Convex deployment. This is the first step in the setup process. SOURCE: https://docs.convex.dev/client/open-api LANGUAGE: bash CODE: ``` npm install convex-helpers ``` -------------------------------- TITLE: Android Project Setup - Empty Activity Template DESCRIPTION: Instructions for creating a new Android application using the 'Empty Activity' template in Android Studio, specifying Kotlin as the Gradle DSL and a minimum SDK of 26. SOURCE: https://docs.convex.dev/quickstart/android LANGUAGE: text CODE: ``` 1. Choose the "Empty Activity" template 2. Name it "Convex Quickstart" 3. Choose min SDK as 26 4. Choose Kotlin as the Gradle DSL ``` -------------------------------- TITLE: Setup Convex Client in SvelteKit (Svelte) DESCRIPTION: Initializes the Convex client in the main SvelteKit layout (`+layout.svelte`) using the `setupConvex` function from `convex-svelte`, making the client available throughout the application. SOURCE: https://docs.convex.dev/quickstart/svelte LANGUAGE: svelte CODE: ``` {@render children()} ``` -------------------------------- TITLE: Create a new npm project DESCRIPTION: Initializes a new Node.js project and navigates into its directory. This is the first step in setting up a new project that will utilize the Convex framework. SOURCE: https://docs.convex.dev/quickstart/script-tag LANGUAGE: bash CODE: ``` mkdir my-project && cd my-project && npm init -y ``` -------------------------------- TITLE: Fetch and Subscribe to Convex Data (Python) DESCRIPTION: Initializes a ConvexClient using a deployment URL from environment variables and demonstrates fetching data via a query and subscribing to real-time updates. SOURCE: https://docs.convex.dev/quickstart/python LANGUAGE: python CODE: ``` 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 ``` -------------------------------- TITLE: Create React App using npx DESCRIPTION: Initializes a new React project using the create-react-app command-line interface. This sets up the basic structure for a React application. SOURCE: https://docs.convex.dev/client/react/quickstart-create-react-app LANGUAGE: bash CODE: ``` npx create-react-app my-app ``` -------------------------------- TITLE: Clone and Run Convex Rate Limiter Example DESCRIPTION: Instructions to clone the Convex agent repository, navigate to the directory, set up dependencies, and run the rate limiting example to observe its behavior. SOURCE: https://docs.convex.dev/agents/rate-limiting LANGUAGE: bash CODE: ``` git clone https://github.com/get-convex/agent.git cd agent npm run setup npm run example ``` -------------------------------- TITLE: Install AuthKit and Convex Package DESCRIPTION: Installs the necessary AuthKit Next.js SDK and the Convex integration package using npm. These packages are required for authentication flows and Convex integration. SOURCE: https://docs.convex.dev/auth/authkit LANGUAGE: bash CODE: ``` npm install @workos-inc/authkit-nextjs @convex-dev/workos ``` -------------------------------- TITLE: Install Convex CLI DESCRIPTION: Installs the Convex command-line interface using npm. This is the first step to begin developing with Convex. SOURCE: https://docs.convex.dev/understanding/workflow LANGUAGE: bash CODE: ``` npm i convex ``` -------------------------------- TITLE: GET Messages by Author Endpoint Example DESCRIPTION: An example of a GET endpoint that retrieves messages filtered by author. SOURCE: https://docs.convex.dev/functions/http-actions LANGUAGE: APIDOC CODE: ``` ## GET /getMessagesByAuthor ### Description Retrieves messages associated with a specific author. ### Method GET ### Endpoint /getMessagesByAuthor ### Parameters #### Path Parameters None #### Query Parameters - **author** (string) - Required - The author whose messages should be retrieved. #### Request Body None ### Request Example None ### Response #### Success Response (200) - **messages** (array) - A list of messages matching the author. #### Response Example ```json { "messages": [ { "id": "msg_123", "author": "User 123", "body": "Example message content" } ] } ``` ``` -------------------------------- TITLE: Clone Convex Tutorial Repo and Install Dependencies DESCRIPTION: This code snippet clones the Convex tutorial repository from GitHub and installs the necessary project dependencies using npm. SOURCE: https://docs.convex.dev/tutorial/reactor LANGUAGE: shell CODE: ``` git clone https://github.com/get-convex/convex-tutorial.git cd convex-tutorial npm install ``` -------------------------------- TITLE: GET Messages by Author Path Suffix Endpoint Example DESCRIPTION: An example of a GET endpoint that uses a path prefix to capture a variable part of the URL for filtering messages by author. SOURCE: https://docs.convex.dev/functions/http-actions LANGUAGE: APIDOC CODE: ``` ## GET /getAuthorMessages/{authorId} ### Description Retrieves messages using a path suffix to identify the author. ### Method GET ### Endpoint /getAuthorMessages/:authorId ### Parameters #### Path Parameters - **authorId** (string) - Required - The identifier for the author. #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **messages** (array) - A list of messages matching the author ID. #### Response Example ```json { "messages": [ { "id": "msg_456", "author": "User 456", "body": "Another message" } ] } ``` ``` -------------------------------- TITLE: Create Nuxt App DESCRIPTION: Initializes a new Nuxt application using npm. This command sets up the basic structure for a Nuxt project. SOURCE: https://docs.convex.dev/quickstart/nuxt LANGUAGE: bash CODE: ``` npm create nuxt@latest my-nuxt-app ``` -------------------------------- TITLE: Update app/routes/__root.tsx for Convex Integration DESCRIPTION: Modifies the root route component in TanStack Start to include a QueryClient in the router context, making React Query accessible throughout the application. This involves importing necessary components from React Query and TanStack Start, defining the root route with context, and setting up the main component and document structure. SOURCE: https://docs.convex.dev/quickstart/tanstack-start LANGUAGE: typescript CODE: ``` import { QueryClient } from "@tanstack/react-query"; import { createRootRouteWithContext } from "@tanstack/react-router"; import { Outlet, ScrollRestoration } from "@tanstack/react-router"; import { Meta, Scripts } from "@tanstack/start"; 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} ); } ``` -------------------------------- TITLE: Install AuthKit and Convex Packages DESCRIPTION: Installs the necessary AuthKit React SDK and the Convex WorkOS integration package. These packages provide the components and hooks required for integrating WorkOS authentication with your Convex backend and React frontend. SOURCE: https://docs.convex.dev/auth/authkit LANGUAGE: bash CODE: ``` npm install @workos-inc/authkit-react @convex-dev/workos ``` -------------------------------- TITLE: Use Agent in Convex Action for Weather DESCRIPTION: Demonstrates how to use the defined Agent within a Convex action to get weather information for a specified city. It creates a thread, prompts the agent with a question, and returns the text response. Ensure `npx convex dev` has been run to generate necessary component code. SOURCE: https://docs.convex.dev/agents/getting-started LANGUAGE: typescript CODE: ``` 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; }, }); ``` -------------------------------- TITLE: Create React App with Vite and TypeScript DESCRIPTION: Initializes a new React project using Vite with a TypeScript template. SOURCE: https://docs.convex.dev/quickstart/react LANGUAGE: bash CODE: ``` npm create vite@latest my-app -- --template react-ts ``` -------------------------------- TITLE: Configure Router for Convex Client and QueryClient DESCRIPTION: Sets up the TanStack Router with Convex integration by creating a ConvexClient and ConvexQueryClient. It wires these clients into a ConvexProvider and configures default query options for React Query to use Convex's hashing and query functions. SOURCE: https://docs.convex.dev/quickstart/tanstack-start LANGUAGE: typescript CODE: ``` import { createRouter as createTanStackRouter } 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 createRouter() { 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 ( createTanStackRouter ({ routeTree, defaultPreload: "intent", context: { queryClient }, Wrap: ({ children }) => ( {children} ), }), queryClient, ); return router; } declare module "@tanstack/react-router" { interface Register { router: ReturnType; } } ``` -------------------------------- TITLE: Configure Agent Component in convex.config.ts DESCRIPTION: Configures the Agent component within your Convex project by importing and using the agent module in the `convex.config.ts` file. This step is crucial for enabling the agent functionality. SOURCE: https://docs.convex.dev/agents/getting-started LANGUAGE: typescript CODE: ``` // 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; ``` -------------------------------- TITLE: Install Project Dependencies with npm DESCRIPTION: Installs all necessary project dependencies using npm. Ensure you have Node.js and npm installed. SOURCE: https://docs.convex.dev/chef LANGUAGE: bash CODE: ``` npm i ``` -------------------------------- TITLE: Fetch Data from Convex in Rust Application DESCRIPTION: Connects to the Convex deployment URL, queries the 'tasks:get' API using a ConvexClient, and prints the results. It loads environment variables using dotenvy. SOURCE: https://docs.convex.dev/quickstart/rust LANGUAGE: rust CODE: ``` 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:#?}"); } ``` -------------------------------- TITLE: Define a Convex Agent with OpenAI DESCRIPTION: Defines a new Agent instance using the Convex Agent SDK. It specifies the agent's name, language model (OpenAI's GPT-4o mini), instructions, available tools (getWeather, getGeocoding), and a maximum step limit for its execution. SOURCE: https://docs.convex.dev/agents/getting-started LANGUAGE: typescript CODE: ``` 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, }); ``` -------------------------------- TITLE: Initialize Convex Client and Provider (React) DESCRIPTION: Sets up the Convex client using `ConvexReactClient` and integrates it into the React application via `ConvexProvider`. This makes Convex services accessible throughout the app. SOURCE: https://docs.convex.dev/client/react/quickstart-create-react-app LANGUAGE: javascript CODE: ``` import { ConvexProvider, ConvexReactClient } from "convex/react"; const convex = new ConvexReactClient(process.env.REACT_APP_CONVEX_URL); root.render( ); ``` -------------------------------- TITLE: Create Next.js App DESCRIPTION: Initializes a new Next.js application with the Pages Router and JavaScript. This command sets up the basic project structure. SOURCE: https://docs.convex.dev/client/react/nextjs-pages-router/quickstart LANGUAGE: bash CODE: ``` npx create-next-app@latest my-app --no-app --js ``` -------------------------------- TITLE: Create Next.js App DESCRIPTION: Initializes a new Next.js application using the create-next-app CLI tool. This command sets up a basic Next.js project structure. SOURCE: https://docs.convex.dev/quickstart/nextjs LANGUAGE: bash CODE: ``` npx create-next-app@latest my-app ``` -------------------------------- TITLE: Running Convex Dev in Agent Mode (bun) DESCRIPTION: This snippet demonstrates initializing Convex development in agent mode using bun. It installs dependencies and starts the Convex development server with anonymous agent permissions, similar to the npm version but using bun. SOURCE: https://docs.convex.dev/ai LANGUAGE: bash CODE: ``` bun i CONVEX_AGENT_MODE=anonymous bun x convex dev --once ``` -------------------------------- TITLE: Install Clerk Next.js SDK DESCRIPTION: Installs the necessary Clerk SDK for Next.js applications using npm. SOURCE: https://docs.convex.dev/auth/clerk LANGUAGE: bash CODE: ``` npm install @clerk/nextjs ``` -------------------------------- TITLE: Start Convex development server DESCRIPTION: Launches the Convex development server, which prompts for login, project creation, and deployment URL saving. It also generates a 'convex/' folder for backend functions and syncs them with the cloud. SOURCE: https://docs.convex.dev/quickstart/bun LANGUAGE: bash CODE: ``` bunx convex dev ``` -------------------------------- TITLE: Embed Convex client in HTML for data retrieval DESCRIPTION: Integrates the Convex client library into an HTML page to fetch and display data from Convex. It initializes the client with a provided Convex URL and sets up a listener to log task texts whenever the 'tasks:get' query is updated. SOURCE: https://docs.convex.dev/quickstart/script-tag LANGUAGE: html CODE: ``` ``` -------------------------------- TITLE: Run Python Script to Load Data DESCRIPTION: Executes the Python script that interacts with Convex to fetch and display data. SOURCE: https://docs.convex.dev/quickstart/python LANGUAGE: bash CODE: ``` venv/bin/python -m main ``` -------------------------------- TITLE: Display Data in React App (TypeScript/React Query) DESCRIPTION: Fetches and displays data from the Convex backend using `useSuspenseQuery` from React Query and the `convexQuery` helper. The component maps over the data to render each task's text. SOURCE: https://docs.convex.dev/quickstart/tanstack-start LANGUAGE: typescript CODE: ``` 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}
))}
); } ``` -------------------------------- TITLE: Start Convex MCP Server DESCRIPTION: This command starts the Convex MCP server, enabling AI agents to connect and interact with your Convex deployment. It requires Node.js and npm. SOURCE: https://docs.convex.dev/ai/convex-mcp-server LANGUAGE: bash CODE: ``` npx -y convex@latest mcp start ``` -------------------------------- TITLE: Create Python Virtual Environment DESCRIPTION: Creates a new virtual environment for a Python project using the 'venv' module. SOURCE: https://docs.convex.dev/quickstart/python LANGUAGE: bash CODE: ``` python3 -m venv my-app/venv ``` -------------------------------- TITLE: Install Convex Test Dependencies (npm) DESCRIPTION: Installs the necessary testing dependencies, including `convex-test`, `vitest`, and `@edge-runtime/vm`, for local Convex backend testing. SOURCE: https://docs.convex.dev/testing/convex-test LANGUAGE: bash CODE: ``` npm install --save-dev convex-test vitest @edge-runtime/vm ``` -------------------------------- TITLE: AuthKit Middleware Setup (middleware.ts) DESCRIPTION: Sets up middleware for AuthKit in a Next.js application to manage authentication state. It defines paths that do not require authentication and configures the route matching for the middleware. SOURCE: https://docs.convex.dev/auth/authkit LANGUAGE: typescript CODE: ``` import { authkitMiddleware } from '@workos-inc/authkit-nextjs'; export default authkitMiddleware({ middlewareAuth: { enabled: true, unauthenticatedPaths: ['/', '/sign-in', '/sign-up'], }, }); export const config = { matcher: [ // Skip Next.js internals and all static files, unless found in search params '/((?!_next|[^?]*\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)', // Always run for API routes '/(api|trpc)(.*)', ], }; ``` -------------------------------- TITLE: Expose Database Query (TypeScript) DESCRIPTION: Defines a server-side Convex query function in TypeScript to retrieve all records from the 'tasks' table. It uses the Convex query API and returns the collected data. SOURCE: https://docs.convex.dev/quickstart/tanstack-start LANGUAGE: typescript CODE: ``` import { query } from "./_generated/server"; export const get = query({ args: {}, handler: async (ctx) => { return await ctx.db.query("tasks").collect(); }, }); ``` -------------------------------- TITLE: Running Convex Dev in Agent Mode (npm) DESCRIPTION: This snippet shows how to initialize Convex development in agent mode using npm. It installs dependencies and starts the Convex development server with anonymous agent permissions, suitable for cloud-based coding agents. SOURCE: https://docs.convex.dev/ai LANGUAGE: bash CODE: ``` npm i CONVEX_AGENT_MODE=anonymous npx convex dev --once ``` -------------------------------- TITLE: Environment Variables Example (.env.local) DESCRIPTION: An example `.env.local` file demonstrating how to set environment variables for frontend use, including the Convex deployment URL and other service keys. Variables intended for the frontend typically require specific prefixes. SOURCE: https://docs.convex.dev/client/react/deployment-urls LANGUAGE: dotenv CODE: ``` 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 ``` -------------------------------- TITLE: Jetpack Compose UI to Display Convex Data DESCRIPTION: A Jetpack Compose Composable function 'Tasks' that connects to a Convex client, subscribes to the 'tasks:get' query, and displays the results in a LazyColumn. SOURCE: https://docs.convex.dev/quickstart/android LANGUAGE: kotlin CODE: ``` @Composable fun Tasks(client: ConvexClient, modifier: Modifier = Modifier) { var tasks: List by remember { mutableStateOf(listOf()) } LaunchedEffect(key1 = "launch") { client.subscribe>("tasks:get").collect { result -> result.onSuccess { remoteTasks -> tasks = remoteTasks } } } LazyColumn( modifier = modifier ) { items(tasks) { Text(text = "Text: ${it.text}, Completed?: ${it.isCompleted}") } } } ``` -------------------------------- TITLE: TanStack Start Route with Convex Loader and useSuspenseQuery DESCRIPTION: Shows how to add a loader to a TanStack Start route to prefetch Convex data using `ensureQueryData` and then render the data with `useSuspenseQuery`. SOURCE: https://docs.convex.dev/client/react/tanstack-start LANGUAGE: javascript CODE: ``` 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) => ( ))}
); }, }) ``` -------------------------------- TITLE: Create SvelteKit App DESCRIPTION: Creates a new SvelteKit application using npm, with specific configurations for a minimal template, TypeScript, and no additional options. SOURCE: https://docs.convex.dev/quickstart/svelte LANGUAGE: bash CODE: ``` npx sv@latest create my-app ``` -------------------------------- TITLE: Reset Expo Project DESCRIPTION: Resets the Expo project to its initial state. This command is useful for cleaning up or starting fresh with the project's default configuration. SOURCE: https://docs.convex.dev/quickstart/react-native LANGUAGE: bash CODE: ``` npm run reset-project ``` -------------------------------- TITLE: Convex Record Example DESCRIPTION: Illustrates a record, which is an object with dynamic keys in Convex. Keys must be ASCII, non-empty, and not start with '$' or '_'. SOURCE: https://docs.convex.dev/database/types LANGUAGE: javascript CODE: ``` {"a": "1", "b": "2"} ``` -------------------------------- TITLE: Development Environment Variables for WorkOS DESCRIPTION: Lists the necessary environment variables for a development setup using WorkOS AuthKit. This includes the Client ID, API Key, a secure cookie password, and the redirect URI for local testing. SOURCE: https://docs.convex.dev/auth/authkit LANGUAGE: dotenv CODE: ``` WORKOS_CLIENT_ID="client_01XXXXXXXXXXXXXXXXXXXXXXXX" WORKOS_API_KEY="sk_test_..." WORKOS_COOKIE_PASSWORD="your_secure_password_here_must_be_at_least_32_characters_long" NEXT_PUBLIC_WORKOS_REDIRECT_URI="http://localhost:3000/callback" ``` -------------------------------- TITLE: Run Convex Development Server (CLI) DESCRIPTION: A command-line instruction to start the Convex development server, which automatically syncs the project's configuration, including authentication settings. SOURCE: https://docs.convex.dev/auth/clerk LANGUAGE: bash CODE: ``` npx convex dev ``` -------------------------------- TITLE: Create Sample Data for Convex Database DESCRIPTION: Defines sample data in JSONL format for import into the Convex database. Each line represents a record with 'text' and 'isCompleted' fields. SOURCE: https://docs.convex.dev/quickstart/react LANGUAGE: json CODE: ``` {"text": "Buy groceries", "isCompleted": true} {"text": "Go for a swim", "isCompleted": true} {"text": "Integrate Convex", "isCompleted": false} ``` -------------------------------- TITLE: Start Local Convex Deployment DESCRIPTION: Initiates a local Convex development deployment. This command must be running for other Convex commands (like `run`) or frontend connections to work with the local deployment. State is stored in `~/.convex/`. SOURCE: https://docs.convex.dev/cli/local-deployments LANGUAGE: bash CODE: ``` npx convex dev --local --once ``` -------------------------------- TITLE: Display Convex Deploy Help DESCRIPTION: Shows all available options for the `npx convex deploy` command, useful for understanding deployment configurations and parameters. SOURCE: https://docs.convex.dev/production/hosting/preview-deployments LANGUAGE: bash CODE: ``` npx convex deploy --help ``` -------------------------------- TITLE: Import Sample Data into Convex Database DESCRIPTION: Imports the sample data from `sampleData.jsonl` into a 'tasks' table within the Convex database using the `convex import` command. SOURCE: https://docs.convex.dev/quickstart/react LANGUAGE: bash CODE: ``` npx convex import --table tasks sampleData.jsonl ``` -------------------------------- TITLE: Run Development Server with npm DESCRIPTION: Starts the development server for your application and sets up Convex if not already configured. This command is used to run your app locally. SOURCE: https://docs.convex.dev/chef LANGUAGE: bash CODE: ``` npm run dev ``` -------------------------------- TITLE: Convex Client Provider Setup in Next.js Layout DESCRIPTION: This code demonstrates how to wrap the application's root layout with ConvexClientProvider in a Next.js application. It imports necessary fonts and sets up metadata, ensuring the Convex client is available throughout the application. SOURCE: https://docs.convex.dev/auth/authkit LANGUAGE: typescript CODE: ``` import type { Metadata } from 'next'; import { Geist, Geist_Mono } from 'next/font/google'; import './globals.css'; import { ConvexClientProvider } from '@/components/ConvexClientProvider'; const geistSans = Geist({ variable: '--font-geist-sans', subsets: ['latin'], }); const geistMono = Geist_Mono({ variable: '--font-geist-mono', subsets: ['latin'], }); export const metadata: Metadata = { title: 'Create Next App', description: 'Generated by create next app', icons: { icon: '/convex.svg', }, }; export default function RootLayout({ children, }: Readonly<{ children: React.ReactNode }>) { return ( {children} ); } ``` -------------------------------- TITLE: Convex Management API Request Example (JavaScript) DESCRIPTION: Demonstrates how to make a request to the Convex Management API using a Bearer token for authorization. This example fetches a list of projects for a specific team. SOURCE: https://docs.convex.dev/management-api LANGUAGE: javascript CODE: ``` const token = "ey...0="; const response = await fetch( "https://api.convex.dev/v1/teams/41/list_projects", { headers: { Authorization: `Bearer ${token}`, }, }, ); console.log(await response.json()); ``` -------------------------------- TITLE: SwiftUI View to Display and Subscribe to Convex Data DESCRIPTION: A SwiftUI View that fetches and displays a list of 'Todo' items from Convex. It uses the `convex.subscribe` method to receive real-time updates from the 'tasks:get' query. SOURCE: https://docs.convex.dev/quickstart/swift LANGUAGE: swift CODE: ``` 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() } } ``` -------------------------------- TITLE: Create React Native App using Expo DESCRIPTION: Initializes a new React Native project using Expo CLI. This command sets up the basic project structure for a React Native application. SOURCE: https://docs.convex.dev/quickstart/react-native LANGUAGE: bash CODE: ``` npx create-expo-app my-app ``` -------------------------------- TITLE: Define Convex Query Function (JavaScript) DESCRIPTION: Exports a Convex query function named 'get' from 'tasks.js' to retrieve all tasks from the database. SOURCE: https://docs.convex.dev/quickstart/python LANGUAGE: javascript CODE: ``` import { query } from "./_generated/server"; export const get = query({ handler: async ({ db }) => { return await db.query("tasks").collect(); }, }); ``` -------------------------------- TITLE: Import Sample Data into Convex Table DESCRIPTION: Imports data from a JSON Lines file into a specified table in the Convex database. This command is used to populate the database with initial or sample records. SOURCE: https://docs.convex.dev/client/react/quickstart-create-react-app LANGUAGE: bash CODE: ``` npx convex import --table tasks sampleData.jsonl ``` -------------------------------- TITLE: Define Convex Query Function (JavaScript) DESCRIPTION: Defines a server-side query function named 'get' within the Convex backend. This function retrieves all records from the 'tasks' table and makes them available via the `api.tasks.get` endpoint. SOURCE: https://docs.convex.dev/client/react/quickstart-create-react-app LANGUAGE: javascript CODE: ``` import { query } from "./_generated/server"; export const get = query({ args: {}, handler: async (ctx) => { return await ctx.db.query("tasks").collect(); }, }); ``` -------------------------------- TITLE: Sample Data for Convex Import DESCRIPTION: Defines sample data in JSON Lines format. This data will be imported into a Convex database table. SOURCE: https://docs.convex.dev/client/react/nextjs-pages-router/quickstart LANGUAGE: json CODE: ``` {"text": "Buy groceries", "isCompleted": true} {"text": "Go for a swim", "isCompleted": true} {"text": "Integrate Convex", "isCompleted": false} ``` -------------------------------- TITLE: Connect to Convex and Execute Query (Node.js) DESCRIPTION: Connects to the Convex development environment using 'ConvexHttpClient' and executes the 'api.tasks.get' query. It loads environment variables using 'dotenv' and logs the query results to the console. SOURCE: https://docs.convex.dev/quickstart/nodejs LANGUAGE: javascript CODE: ``` 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); ``` -------------------------------- TITLE: Install Convex client library with Bun DESCRIPTION: Adds the 'convex' package as a dependency to your Bun project. SOURCE: https://docs.convex.dev/quickstart/bun LANGUAGE: bash CODE: ``` bun add convex ``` -------------------------------- TITLE: Connect Android App to Convex Backend URL DESCRIPTION: Updates the MainActivity's onCreate method to initialize the ConvexClient with the deployment URL and display the Tasks UI. SOURCE: https://docs.convex.dev/quickstart/android LANGUAGE: kotlin CODE: ``` override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() setContent { ConvexQuickstartTheme { Scaffold(modifier = Modifier.fillMaxSize()) { Tasks( client = ConvexClient($YOUR_CONVEX_URL), modifier = Modifier.padding(it) ) } } } } ``` -------------------------------- TITLE: Run Node.js Script to Fetch Data DESCRIPTION: Executes the 'script.js' file using Node.js, which queries the Convex database and logs the retrieved tasks to the terminal. Assumes the script is in the same directory. SOURCE: https://docs.convex.dev/quickstart/nodejs LANGUAGE: bash CODE: ``` node script.js ``` -------------------------------- TITLE: Convex Client Provider Component (TypeScript) DESCRIPTION: Creates a React client component that initializes and provides the Convex client to the application using `` and `ConvexReactClient`. SOURCE: https://docs.convex.dev/quickstart/nextjs LANGUAGE: typescript CODE: ``` "use client"; import { ConvexProvider, ConvexReactClient } from "convex/react"; import { ReactNode } from "react"; const convex = new ConvexReactClient(process.env.NEXT_PUBLIC_CONVEX_URL!); export function ConvexClientProvider({ children }: { children: ReactNode }) { return {children}; } ``` -------------------------------- TITLE: Convex Query Function to Fetch Tasks (TypeScript) DESCRIPTION: Exports a Convex query function named `get` from `convex/tasks.ts`. This function queries the 'tasks' table and returns all collected documents. The function is accessible via `api.tasks.get`. SOURCE: https://docs.convex.dev/quickstart/react LANGUAGE: typescript CODE: ``` import { query } from "./_generated/server"; export const get = query({ args: {}, handler: async (ctx) => { return await ctx.db.query("tasks").collect(); }, }); ``` -------------------------------- TITLE: Convex Database Query Function (JavaScript) DESCRIPTION: Defines a Convex query function named 'get' in JavaScript. This function retrieves all documents from the 'tasks' table. It's declared in `convex/tasks.js` and accessible via `api.tasks.get`. SOURCE: https://docs.convex.dev/client/react/nextjs-pages-router/quickstart LANGUAGE: javascript CODE: ``` import { query } from "./_generated/server"; export const get = query({ args: {}, handler: async (ctx) => { return await ctx.db.query("tasks").collect(); }, }); ``` -------------------------------- TITLE: Connect React App to Convex Backend (TypeScript) DESCRIPTION: Initializes `ConvexReactClient` with the Convex URL and provides it to the `ConvexProvider` to wrap the React application. This makes Convex accessible throughout the app. SOURCE: https://docs.convex.dev/quickstart/react LANGUAGE: typescript CODE: ``` import React from "react"; import ReactDOM from "react-dom/client"; import App from "./App"; import "./index.css"; import { ConvexProvider, ConvexReactClient } from "convex/react"; const convex = new ConvexReactClient(import.meta.env.VITE_CONVEX_URL as string); ReactDOM.createRoot(document.getElementById("root")!).render( , ); ``` -------------------------------- TITLE: Example Audit Log Event for Push Config (JSON) DESCRIPTION: An example of an audit log event detailing a 'push_config' action. It includes the '_topic', '_timestamp', 'action' field, and 'actionMetadata' which specifies added and removed modules. SOURCE: https://docs.convex.dev/production/integrations/log-streams/legacy-event-schema LANGUAGE: json CODE: ``` { "_topic": "_audit_log", "_timestamp": 1695066350531, "action": "push_config", "actionMetadata": { "modules": { "added": ["ffmpeg.js", "fetch.js", "test.js"], "removed": ["removed.js"] } } } ``` -------------------------------- TITLE: Initialize Convex Client in Next.js App DESCRIPTION: Sets up the Convex client and provider in the Next.js application's entry point (`pages/_app.js`). It creates a `ConvexReactClient` instance using the provided URL and wraps the application with `ConvexProvider`. SOURCE: https://docs.convex.dev/client/react/nextjs-pages-router/quickstart LANGUAGE: javascript CODE: ``` 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 ( ); } ``` -------------------------------- TITLE: Install Latest Convex Version DESCRIPTION: Ensures you are using the most recent version of the Convex package. This is a prerequisite for debugging bundle size issues. SOURCE: https://docs.convex.dev/functions/bundling LANGUAGE: bash CODE: ``` npm install convex@latest ``` -------------------------------- TITLE: Install Clerk React SDK (npm) DESCRIPTION: Installs the Clerk React SDK package, providing necessary components and hooks for integrating Clerk authentication into a React application. SOURCE: https://docs.convex.dev/auth/clerk LANGUAGE: bash CODE: ``` npm install @clerk/clerk-react ``` -------------------------------- TITLE: Android Manifest Configuration for Internet Permission DESCRIPTION: This snippet shows how to add the INTERNET permission to the AndroidManifest.xml file, which is necessary for the application to communicate with the Convex backend. SOURCE: https://docs.convex.dev/quickstart/android LANGUAGE: xml CODE: ``` ``` -------------------------------- TITLE: Subscribe to Convex Query with Arguments in Swift DESCRIPTION: Illustrates how to pass arguments to a Convex query subscription. This example shows subscribing to 'colors:get' with a boolean argument `onlyFavorites` set to true. SOURCE: https://docs.convex.dev/client/swift LANGUAGE: swift CODE: ``` let publisher = convex.subscribe(to: "colors:get", with: ["onlyFavorites": true], yielding: [String].self) ``` -------------------------------- TITLE: Create Sample Data for Convex Database DESCRIPTION: Defines sample data in JSON Lines format for importing into the Convex database. Each line represents a JSON object for a database record. SOURCE: https://docs.convex.dev/client/react/quickstart-create-react-app LANGUAGE: json CODE: ``` {"text": "Buy groceries", "isCompleted": true} {"text": "Go for a swim", "isCompleted": true} {"text": "Integrate Convex", "isCompleted": false} ``` -------------------------------- TITLE: POST Message Endpoint Example DESCRIPTION: An example of a POST endpoint that accepts JSON, processes it, and returns a success status. SOURCE: https://docs.convex.dev/functions/http-actions LANGUAGE: APIDOC CODE: ``` ## POST /postMessage ### Description Accepts a JSON payload with 'author' and 'body', processes it using a Convex mutation, and returns a 200 status on success. ### Method POST ### Endpoint /postMessage ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **author** (string) - Required - The author of the message. - **body** (string) - Required - The content of the message. ### Request Example ```json { "author": "User 123", "body": "Hello world" } ``` ### Response #### Success Response (200) Returns a 200 status code with no content on successful processing. #### Response Example ``` (No content) ``` ``` -------------------------------- TITLE: Import Data into Convex Table DESCRIPTION: Imports the sample data from a JSON Lines file into a specified Convex database table. This command assumes 'sampleData.jsonl' contains the data. SOURCE: https://docs.convex.dev/client/react/nextjs-pages-router/quickstart LANGUAGE: bash CODE: ``` npx convex import --table tasks sampleData.jsonl ``` -------------------------------- TITLE: Convex Action Using Default JavaScript Runtime with Fetch DESCRIPTION: An example of a Convex action running in the default JavaScript environment, utilizing the `fetch` API to call a third-party service. This environment is faster due to no cold starts and allows defining other Convex functions in the same file. SOURCE: https://docs.convex.dev/functions/actions LANGUAGE: typescript CODE: ``` import { action } from "./_generated/server"; export const doSomething = action({ args: {}, handler: async () => { const data = await fetch("https://api.thirdpartyservice.com"); // do something with data }, }); ``` -------------------------------- TITLE: Initialize Convex Client in Swift DESCRIPTION: Initializes the ConvexClient instance using a deployment URL obtained from the local environment variables. This client is used to interact with the Convex backend. SOURCE: https://docs.convex.dev/quickstart/swift LANGUAGE: swift CODE: ``` import SwiftUI import ConvexMobile let convex = ConvexClient(deploymentUrl: "YOUR_CONVEX_URL") struct ContentView: View { ... ``` -------------------------------- TITLE: Install ESLint 8 Convex Plugin DESCRIPTION: Installs necessary ESLint plugins for version 8 and configures them in .eslintrc.js to enforce Convex best practices. SOURCE: https://docs.convex.dev/eslint LANGUAGE: bash CODE: ``` npm i @typescript-eslint/eslint-plugin @convex-dev/eslint-plugin ``` LANGUAGE: javascript CODE: ``` module.exports = { extends: [ // Other configurations "plugin:@typescript-eslint/recommended", "plugin:@convex-dev/recommended", ], ignorePatterns: ["node_modules/", "dist/", "build/"], }; ```