### Clone Convex Tutorial Project and Install Dependencies Source: https://docs.convex.dev/tutorial/overview Clone the example project repository from GitHub and install the necessary npm dependencies to start development. ```bash git clone https://github.com/get-convex/convex-tutorial.git cd convex-tutorial npm install ``` -------------------------------- ### Clone Convex Tutorial Project Source: https://docs.convex.dev/tutorial/reactor Clone the example project repository from GitHub and install its dependencies to get started. ```bash git clone https://github.com/get-convex/convex-tutorial.git cd convex-tutorial npm install ``` -------------------------------- ### Run RAG example setup and execution Source: https://docs.convex.dev/agents/rag Clone the RAG repository and run the example to see content ingestion, searching, and text generation in action. ```bash git clone https://github.com/get-convex/rag.git cd rag npm run setup npm run example ``` -------------------------------- ### Running the Agent Example Source: https://docs.convex.dev/llms-full.txt Clone the agent repository, navigate to the directory, and run the setup and development commands. ```bash git clone https://github.com/get-convex/agent.git cd agent npm run setup npm run dev ``` -------------------------------- ### Install AuthKit TanStack Start SDK Source: https://docs.convex.dev/auth/authkit/add-to-app Install the AuthKit TanStack Start SDK using npm in your project's terminal. ```bash npm install @workos/authkit-tanstack-react-start ``` -------------------------------- ### Start Convex MCP Server Source: https://docs.convex.dev/ai/convex-mcp-server Installs and starts the Convex MCP server. This is the basic command for setting up the server. ```bash npx -y convex@latest mcp start ``` -------------------------------- ### Basic HTTP Router Setup Source: https://docs.convex.dev/functions/http-actions Sets up a basic HTTP router with a single GET route at the root path. This is the entry point for HTTP actions. ```typescript import { httpRouter } from "convex/server"; import { httpAction } from "./_generated/server"; const http = httpRouter(); http.route({ path: "/", method: "GET", handler: httpAction(async (ctx, request) => { return new Response(`Hello from ${request.url}`); }), }); export default http; ``` -------------------------------- ### Example Import Declarations Source: https://docs.convex.dev/quickstart/android Example import declarations for common Android Jetpack Compose and Activity components used in the quickstart. ```kotlin import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items ``` -------------------------------- ### Setup Script for Agent Mode (bun) Source: https://docs.convex.dev/ai/overview This script initializes a project and starts Convex in development mode for agents using bun. It requires full internet access to download the Convex binary. ```bash bun i bun x convex dev --once ``` -------------------------------- ### Setup Script for Agent Mode (npm) Source: https://docs.convex.dev/ai/overview This script initializes a project and starts Convex in development mode for agents using npm. It includes an optional step to set environment variables from a file. ```bash npm i # npx convex init # allows setting environment variables before pushing # npx convex env set --from-file ./path/to/.env.agent (optional) npx convex dev --once ``` -------------------------------- ### Setup ESLint (.eslintrc.js) Source: https://docs.convex.dev/llms-full.txt Install necessary ESLint plugins and extend them in your .eslintrc.js file for older ESLint configurations. ```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/"], }; ``` -------------------------------- ### Basic HTTP Action Setup Source: https://docs.convex.dev/functions/http-actions This snippet shows the basic structure for defining an HTTP router and a simple GET route at the root path. ```APIDOC ## GET / ### Description A basic HTTP action that responds with a greeting. ### Method GET ### Endpoint / ### Request Example (No request body for GET) ### Response #### Success Response (200) - **body** (string) - A greeting message. #### Response Example ``` Hello from https://.convex.site/ ``` ``` -------------------------------- ### Manual Setup for New Convex Project with Codex Source: https://docs.convex.dev/llms-full.txt Manually scaffold a new Convex project before integrating Codex. This involves creating the project, navigating into it, installing Convex AI files, and then launching Codex. ```bash npm create convex@latest my-app cd my-app npx convex ai-files install codex ``` -------------------------------- ### Initialize New Convex Project with Codex Source: https://docs.convex.dev/ai/using-codex Use this command to start a new Convex project with Codex, which handles project creation, Convex setup, and local backend provisioning. ```bash codex "build me a todo app with Convex" Give the agent full access (dangerous, skips all approval prompts) ``` -------------------------------- ### Install Convex Libraries and Dependencies Source: https://docs.convex.dev/quickstart/python Navigates into the app directory, initializes npm, installs Convex npm package, and then installs Python client and dotenv libraries. ```bash cd my-app && npm init -y && npm install convex && venv/bin/pip install convex python-dotenv ``` -------------------------------- ### Install Convex Packages Source: https://docs.convex.dev/llms-full.txt Install the necessary Convex client and server libraries for your SvelteKit project. ```bash cd my-app && npm install convex convex-svelte ``` -------------------------------- ### Install Action Cache Source: https://www.convex.dev/components/action-cache Install the Action Cache component using npm. ```bash npm install @convex-dev/action-cache ``` -------------------------------- ### Example App Codegen and Deploy Source: https://docs.convex.dev/components/authoring Generate code for the example app and deploy it. Optionally, use '--typecheck-components' to verify component types. ```bash npx convex dev --typecheck-components # optionally type-check the components ``` -------------------------------- ### Setup Script for Codex with Convex Cloud Source: https://docs.convex.dev/llms-full.txt A setup script for running Codex with Convex in a cloud environment using Agent Mode. This installs dependencies and starts a local Convex development server. ```bash npm i npx convex dev --once ``` -------------------------------- ### Count Total Scores Source: https://convex.dev/components/aggregate Use this to get the total number of entries in the aggregate. No specific setup is required beyond installing the component. ```javascript aggregate.count(ctx) ``` -------------------------------- ### Initialize Bun Project Source: https://docs.convex.dev/quickstart/bun Create a new Bun project directory and initialize it with default settings. ```bash mkdir my-project && cd my-project && bun init -y ``` -------------------------------- ### Run Convex Agent Example Source: https://docs.convex.dev/agents/files Commands to clone, set up, and run the Convex agent example project locally. ```bash git clone https://github.com/get-convex/agent.git cd agent npm run setup npm run dev ``` -------------------------------- ### Set Up Cloud Development Environment with Convex Source: https://docs.convex.dev/ai/using-claude-code Configure a cloud development environment for Claude Code with Convex. This setup script installs dependencies and starts a local Convex backend for agent interaction without requiring manual login. ```bash npm i npx convex dev --once ``` -------------------------------- ### Install Convex and React Query Dependencies Source: https://docs.convex.dev/llms-full.txt Install the necessary Convex and React Query packages for your TanStack Start site. ```bash npm install convex @convex-dev/react-query @tanstack/react-router-ssr-query @tanstack/react-query ``` -------------------------------- ### Run Convex Auth Initialization Command Source: https://labs.convex.dev/auth/setup Execute this command to set up your project for authentication using the Convex Auth library. For manual setup, refer to the provided link. ```bash npx @convex-dev/auth ``` -------------------------------- ### Install Convex Client and Server Library Source: https://docs.convex.dev/client/nextjs/pages-router/quickstart Navigate into your project directory and install the `convex` package. ```bash cd my-app && npm install convex ``` -------------------------------- ### Defining a GET HTTP Action with Path Suffix Source: https://docs.convex.dev/functions/http-actions This example shows how to define a GET HTTP action that uses a path prefix to capture dynamic parts of the URL. ```APIDOC ## GET /getAuthorMessages/{userId} ### Description Retrieves messages for a specific author using a path suffix. The `{userId}` part of the path is captured and can be used within the handler. ### Method GET ### Endpoint /getAuthorMessages/{userId} ### Parameters #### Path Parameters - **userId** (string) - Required - The identifier of the author whose messages are to be retrieved. This is captured from the URL path. ### Request Example (No request body for GET) ### Response #### Success Response (200) - **messages** (Array) - A list of messages associated with the specified author. #### Response Example ```json { "messages": [ { "_id": "messageId1", "author": "User 123", "body": "Message content 1" }, { "_id": "messageId2", "author": "User 123", "body": "Message content 2" } ] } ``` ``` -------------------------------- ### Convex Test Suite Example Source: https://stack.convex.dev/testing-with-local-oss-backend An example of a Vitest test suite using `ConvexTestingHelper` to interact with Convex functions. It includes setup and teardown logic to clear data after each test. ```typescript import { api } from "./_generated/api"; import { ConvexTestingHelper } from "convex-helpers/testing"; describe("testingExample", () => { let t: ConvexTestingHelper; beforeEach(() => { t = new ConvexTestingHelper(); }); afterEach(async () => { await t.mutation(api.testingFunctions.clearAll, {}); await t.close(); }); test("can only read own notes", async () => { const personASessionId = "Person A"; await t.mutation(api.notes.add, { sessionId: personASessionId, note: "Hello from Person A" }); await t.mutation(api.notes.add, { sessionId: personASessionId, note: "Hello again from Person A" }); const personBSessionId = "Person B"; await t.mutation(api.notes.add, { sessionId: personBSessionId, note: "Hello from Person B" }); const personANotes = await t.query(api.notes.list, { sessionId: personASessionId }); expect(personANotes.length).toEqual(2); }); }); ``` -------------------------------- ### Initialize TanStack Start Project with Convex Source: https://docs.convex.dev/quickstart/tanstack-start Use this command to quickly set up a new TanStack Start project pre-configured with Convex. ```bash npm create convex@latest -- -t tanstack-start ``` -------------------------------- ### Define a Durable Workflow with AI Agents Source: https://stack.convex.dev/ai-agents Orchestrate AI agent actions within a durable workflow. This example shows how to create a thread, get a weather forecast, and then get fashion advice based on the weather. ```tsx import { components, internal } from "./_generated/api"; import { WorkflowManager } from "@convex-dev/workflow"; const workflow = new WorkflowManager(components.workflow); export const weatherAgentWorkflow = workflow.define({ args: { location: v.string(), userId: v.id("users") }, handler: async (step, { location, userId }): Promise => { const { threadId } = await step.runMutation( internal.example.createThread, { userId }, ); await step.runAction( internal.example.getForecast, { prompt: `What is the weather in ${location}?`, threadId }, { retry: true }, ); const { object } = await step.runAction( internal.example.getFashionAdvice, { prompt: `What should I wear based on the weather?`, threadId }, { runAfter: 2 * SECOND }, ); } ``` -------------------------------- ### TanStack Start Router Configuration with Convex Source: https://docs.convex.dev/llms-full.txt This snippet shows the setup for a TanStack Start router, integrating Convex for data fetching and authentication. It configures ConvexReactClient and ConvexQueryClient, and sets up query options for seamless integration with React Query. ```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 { setupRouterSsrQueryIntegration } from '@tanstack/react-router-ssr-query' import { ConvexProvider, ConvexReactClient } from 'convex/react' import { ConvexQueryClient } from '@tanstack/convex-react-query' import { QueryClient } from '@tanstack/react-query' export function getRouter() { 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 = createTanStackRouter({ routeTree, defaultPreload: 'intent', defaultErrorComponent: DefaultCatchBoundary, defaultNotFoundComponent: () => , context: { queryClient, convexClient: convex, convexQueryClient }, scrollRestoration: true, Wrap: ({ children }) => ( {children} ), }) setupRouterSsrQueryIntegration({ router, queryClient }) return router } declare module '@tanstack/react-router' { interface Register { router: ReturnType } } ``` -------------------------------- ### React Starter Kit (RSK) Overview Source: https://www.convex.dev/templates A modern, production-ready SaaS starter template for full-stack React applications. It features React Router v7, Convex, Clerk, Polar.sh, and AI chat integration, ready for Vercel deployment. ```text A modern, production-ready SaaS starter template for building full-stack React applications using React Router v7, Convex, Clerk, and Polar.sh. Ready for Vercel deployment with built-in AI chat capabilities. Features: - React Router v7 - Modern full-stack React framework with SSR - Hot Module Replacement (HMR) - Fast development experience - Asset bundling and optimization - Production-ready builds - Data loading and mutations - Built-in loader/action patterns - TypeScript by default - Type safety throughout - TailwindCSS v4 - Modern utility-first CSS - Authentication with Clerk - Complete user management - Subscription management with Polar.sh - Billing and payments - Real-time database with Convex - Serverless backend - AI Chat Integration - OpenAI-powered chat functionality - Interactive Dashboard - User management and analytics - Webhook handling - Payment and subscription events - Responsive Design - Mobile-first approach - Vercel Deployment Ready - One-click deployment ``` -------------------------------- ### List Tasks Query Source: https://docs.convex.dev/llms-full.txt Initiates a query on the 'tasks' table to retrieve all tasks. This is a basic example of starting a query in Convex. ```typescript import { query } from "./_generated/server"; export const listTasks = query({ args: {}, handler: async (ctx) => { const tasks = await ctx.db.query("tasks").collect(); // do something with `tasks` }, }); ``` -------------------------------- ### Conductor `conductor.json` Setup Source: https://docs.convex.dev/llms-full.txt Add this setup command to your project's `conductor.json` to automate dev deployment creation for each Conductor workspace. Replace placeholders as needed. ```json { "scripts": { "setup": "npm ci && npx convex deployment create --type=dev my-team:my-project:dev/$USER-conductor/$CONDUCTOR_WORKSPACE_NAME --select" } } ``` -------------------------------- ### Create a Remix App Source: https://docs.convex.dev/quickstart/remix Use this command to initialize a new Remix project. ```bash npx create-remix@latest my-remix-app ``` -------------------------------- ### Create Nuxt Application Source: https://docs.convex.dev/llms-full.txt Use npm to create a new Nuxt application. Skip installing official modules for this quickstart. ```bash npm create nuxt@latest my-nuxt-app ``` -------------------------------- ### Count Documents with Limits or Denormalization in Convex Source: https://docs.convex.dev/understanding/best-practices Instead of collecting all documents to count them, use `take` to limit results or denormalize counts into a separate table. The '❌' example fetches all documents to get a count, while the '✅' examples show more efficient methods. ```typescript // ❌ -- potentially unbounded const watchedMovies = await ctx.db .query("watchedMovies") .withIndex("by_user", (q) => q.eq("user", "Tom")) .collect(); const numberOfWatchedMovies = watchedMovies.length; ``` ```typescript // ✅ -- Show "99+" instead of needing to load all documents const watchedMovies = await ctx.db .query("watchedMovies") .withIndex("by_user", (q) => q.eq("user", "Tom")) .take(100); const numberOfWatchedMovies = watchedMovies.length === 100 ? "99+" : watchedMovies.length.toString(); ``` ```typescript // ✅ -- Denormalize the number of watched movies in a separate table const watchedMoviesCount = await ctx.db .query("watchedMoviesCount") .withIndex("by_user", (q) => q.eq("user", "Tom")) .unique(); ``` -------------------------------- ### Install Convex Client Library Source: https://docs.convex.dev/quickstart/react-native Navigate to your app directory and install the Convex package to enable communication with your Convex backend. ```bash cd my-app && npm install convex ``` -------------------------------- ### Example Preview Deploy Key Source: https://docs.convex.dev/cli/deploy-key-types A preview deploy key enables deploying code to a preview branch, altering the behavior of the standard deploy command. ```text preview:team-slug:project-slug|eyJ2...0= ``` -------------------------------- ### Get Auth Token with Auth0 Source: https://docs.convex.dev/client/nextjs/app-router/server-rendering Implement `getAuthToken` using Auth0's server-side authentication. This example requires v4.3 or later of `@auth0/nextjs-auth0`. ```typescript // You'll need v4.3 or later of @auth0/nextjs-auth0 import { getSession } from '@auth0/nextjs-auth0'; export async function getAuthToken() { const session = await getSession(); const idToken = session.tokenSet.idToken; return idToken; } ``` -------------------------------- ### Create Dev Deployment and Select Source: https://docs.convex.dev/cli/reference/deployment Creates a new dev deployment and immediately selects it for use. This updates the .env.local file. ```bash npx convex deployment create dev/my-new-feature --type dev --select ``` -------------------------------- ### Product Support Workflow Example Source: https://stack.convex.dev/durable-workflows-and-strong-guarantees This workflow demonstrates fetching customer history, creating a ticket, fetching context, and generating a resolution using AI and multiple tools. ```typescript async function supportWorkflow(ctx, { user, message }) { // 1: Fetch the customer history from the database const userHistory = await ctx.runQuery(customerHistory, { user }); const summary = await summarizeHistoryWithAI({ message, userHistory }); // 2: Create a CX (Customer Experience) ticket with the summary for the user. const ticketId = await ctx.runMutation(createTicket, { summary, user, message }); // 3. Fetch related context from a vector + transactional database const context = await fetchSupportContext(ctx, { summary, message, user }); await ctx.runMutation(updateTicket, { ticketId, status: "in-progress", context }); // 4. Generate a proposed resolution via an LLM call with multiple tools const resolution = await getAIResolution({ context, userHistory, summary }); await ctx.runMutation(updateTicket, { ticketId, status: "resolution", resolution }); // 5. ``` -------------------------------- ### Log out of Convex CLI Source: https://docs.convex.dev/cli/reference/logout Use this command to log out of your current Convex session on the machine. No specific setup is required beyond having the Convex CLI installed. ```bash npx convex logout [options] ``` -------------------------------- ### Convex Workflow Header Example Source: https://stack.convex.dev/durable-workflows-and-strong-guarantees This snippet shows a header for a Convex workflow, likely indicating the start of a workflow definition or a section related to workflow execution. ```typescript 2b:[\"$\",\"h3\",null,{\"id\":\"the-problems-you-dont-want-to-think-about\",\"className\":\"mb-2 scroll-target pt-4 font-display text-2xl\",\"children\":[\"The problems you don’t want to think about\",[\"$\",\"a\",null,{\"href\":\"#the-problems-you-dont-want-to-think-about\",\"className\":\"text-neutral-n9 hover:text-neutral-n7\",\"children\":[\"$\",\"svg\",null,{\"width\":\"15\",\"height\":\"15\",\"viewBox\":\"0 0 15 15\",\"fill\":\"none\",\"xmlns\":\"http://www.w3.org/2000/svg\",\"className\":\"relative -top-0.5 ml-2 inline-block h-5 w-5\",\"ref\":\"$undefined\",\"children\":[\"$\",\"path\",null,{\"d\":\"$79\",\"fill\":\"currentColor\",\"fillRule\":\"evenodd\",\"clipRule\":\"evenodd\"}]}]}]}]} ``` -------------------------------- ### Create Preview Deployment with Initial Data Seeding Source: https://docs.convex.dev/production/multiple-deployments Automatically create sample data when a preview deployment is created by specifying a Convex function to run. The function is only executed if a new preview deployment is created. ```bash npx convex deploy --preview-create="my-preview-deployment-name" --preview-run= ``` -------------------------------- ### Run the Android app Source: https://docs.convex.dev/quickstart/android Instructions on how to run the Android application from the IDE after setup. ```text From the IDE menu choose "Run" > "Run 'app'" ``` -------------------------------- ### Executing a Convex Mutation with useMutation Source: https://docs.convex.dev/llms-full.txt Use the useMutation hook to get a stable function reference for executing a Convex mutation. This example shows how to create a task mutation. ```typescript import { useMutation } from "convex/react"; import { api } from "../convex/_generated/api"; function CreateTask() { const createTask = useMutation(api.tasks.create); const handleClick = async () => { await createTask({ text: "New task" }); }; return ; } ``` -------------------------------- ### Convex Trigger Example Source: https://stack.convex.dev/triggers This snippet demonstrates a basic Convex trigger setup. It's part of a larger system where inserting data can implicitly call registered triggers. ```typescript self.__next_f.push([1,"5c:[\"$\",\"h3\",null,{\"id\":\"consider-explicit-function-calls-instead\",\"className\":\"mb-2 scroll-target pt-4 font-display text-2xl\",\"children\":[\"Consider explicit function calls instead\",[\"$\",\"a\",null,{\"href\":\"#consider-explicit-function-calls-instead\",\"className\":\"text-neutral-n9 hover:text-neutral-n7\",\"children\":[\"$\",\"svg\",null,{\"width\":\"15\",\"height\":\"15\",\"viewBox\":\"0 0 15 15\",\"fill\":\"none\",\"xmlns\":\"http://www.w3.org/2000/svg\",\"className\":\"relative -top-0.5 ml-2 inline-block h-5 w-5\",\"ref\":\"$undefined\",\"children\":[\"$\",\"path\",null,{\"d\":\"$81\",\"fill\":\"currentColor\",\"fillRule\":\"evenodd\",\"clipRule\":\"evenodd\"}]} inaly]} inaly]} inaly]\n"]) ``` -------------------------------- ### Install Project Dependencies Source: https://docs.convex.dev/chef/migration-guide Navigate to your app folder in the terminal and run this command to install all project dependencies. ```bash cd ~/ npm i ``` -------------------------------- ### Install and Use NPM Packages in Convex Queries Source: https://docs.convex.dev/llms-full.txt Integrate external NPM packages into your Convex functions. This example demonstrates using the Faker.js library to generate random names. ```bash npm install @faker-js/faker ``` ```typescript import { query } from "./_generated/server"; import { faker } from "@faker-js/faker"; export const randomName = query({ args: {}, handler: () => { faker.seed(); return faker.person.fullName(); }, }); ``` -------------------------------- ### Example Query: Get Task List Source: https://docs.convex.dev/llms-full.txt Defines a query to retrieve the last 100 tasks for a specific task list. It reads data from the 'tasks' table using an index. ```typescript import { query } from "./_generated/server"; import { v } from "convex/values"; // Return the last 100 tasks in a given task list. export const getTaskList = query({ args: { taskListId: v.id("taskLists") }, handler: async (ctx, args) => { const tasks = await ctx.db .query("tasks") .withIndex("by_task_list_id", (q) => q.eq("taskListId", args.taskListId)) .order("desc") .take(100); return tasks; }, }); ``` -------------------------------- ### Start Convex Dev Deployment Source: https://docs.convex.dev/quickstart/bun Initialize Convex dev deployment, which prompts GitHub login, creates a project, and sets up the convex/ folder for backend functions. ```bash bunx convex dev ``` -------------------------------- ### Get URL for Stored File in Convex Source: https://docs.convex.dev/llms-full.txt Retrieve a URL for a stored file using `ctx.storage.getUrl`. This URL can then be used, for example, to return to the client. File metadata can be accessed via `ctx.db.system.get`. ```typescript // Get a URL for a stored file: const url = await ctx.storage.getUrl(storageId); if (url) { // Use the URL (e.g. return it to the client) } // Get file metadata via the system table (preferred over deprecated getMetadata): const metadata = await ctx.db.system.get("_storage", storageId); // metadata: { _id, _creationTime, sha256, size, contentType? } ``` -------------------------------- ### Initialize and Run MCP Server Source: https://docs.convex.dev/cli/reference/mcp Basic command to start the Model Context Protocol server for Convex. ```bash npx convex mcp [options] [command] ``` -------------------------------- ### Define HTTP Routes with HttpRouter Source: https://docs.convex.dev/llms-full.txt Example of how to use HttpRouter to define POST and GET routes. Routes can be defined inline or imported from other files. Ensure the router is the default export of `convex/http.js`. ```typescript import { httpRouter } from "convex/server"; import { getMessagesByAuthor } from "./getMessagesByAuthor"; import { httpAction } from "./_generated/server"; const http = httpRouter(); // HTTP actions can be defined inline... http.route({ path: "/message", method: "POST", handler: httpAction(async ({ runMutation }, request) => { const { author, body } = await request.json(); await runMutation(api.sendMessage.default, { body, author }); return new Response(null, { status: 200, }); }) }); // ...or they can be imported from other files. http.route({ path: "/getMessagesByAuthor", method: "GET", handler: getMessagesByAuthor, }); // Convex expects the router to be the default export of `convex/http.js`. export default http; ``` -------------------------------- ### Execute a Convex Mutation with useMutation Source: https://docs.convex.dev/api/modules/react Use the useMutation hook to get a stable function for executing a Convex mutation. This example shows how to create a task mutation and trigger it on button click. ```typescript import { useMutation } from "convex/react"; import { api } from "../convex/_generated/api"; function CreateTask() { const createTask = useMutation(api.tasks.create); const handleClick = async () => { await createTask({ text: "New task" }); }; return ; } ``` -------------------------------- ### Deploying Convex Functions for Preview Environments Source: https://docs.convex.dev/llms-full.txt Use this command to deploy Convex functions and optionally run a setup function for preview environments. This ensures preview deployments are isolated and do not affect production or development data. ```bash npx convex deploy --cmd 'npm run build' --preview-run 'functionName' ```