Convex

From TerminalSkills/skills · View interactive version

Convex is an AI agent skill from the GitHub repository TerminalSkills/skills. Convex is a reactive backend where the database, server functions and file storage are written in TypeScript and query results update live in every connected client. Use when building a Convex app: schema and indexes, queries, mutations and actions, useQuery and useMutation in React, auth, paginatio

How to use this skill

Skill file

Convex

Overview

Convex runs your TypeScript server functions next to a transactional document database. Queries are reactive: a useQuery subscription re-renders when the data it read changes, with no WebSocket, polling or cache-invalidation code. Mutations are ACID transactions with optimistic concurrency control. Functions live in the convex/ folder and are called through the generated api object.

Three function kinds: query (read-only, reactive, deterministic), mutation (transactional writes), action (may call external APIs, not transactional, can run queries and mutations through ctx.runQuery and ctx.runMutation). Use internalQuery, internalMutation and internalAction for functions that only other Convex functions may call.

Instructions

Step 1: Create the project

$ npm create convex@latest          # new app with Convex wired in
$ npm install convex                # or add to an existing app
$ npx convex dev                    # logs in, creates a deployment, syncs convex/ and writes convex/_generated

npx convex dev keeps running and pushes every change to your dev deployment; it writes the deployment URL to .env.local (for Vite, VITE_CONVEX_URL). Never commit deploy keys; production deploys use npx convex deploy with CONVEX_DEPLOY_KEY set in CI.

Step 2: Schema and indexes

// convex/schema.ts
import { defineSchema, defineTable } from "convex/server";
import { v } from "convex/values";

export default defineSchema({
  messages: defineTable({
    channel: v.string(),
    author: v.string(),
    body: v.string(),
    imageId: v.optional(v.id("_storage")),
  })
    .index("by_channel", ["channel"])
    .searchIndex("search_body", { searchField: "body", filterFields: ["channel"] }),
});

Every document also gets _id and _creationTime; by_channel implicitly ends with _creationTime, so results come back in creation order. Use .withIndex(...) rather than .filter(...) for anything that must scale.

Step 3: Functions

Functions take an object with args validators and a handler.

// convex/messages.ts
import { query, mutation } from "./_generated/server";
import { v } from "convex/values";
import { paginationOptsValidator } from "convex/server";

export const list = query({
  args: { channel: v.string(), paginationOpts: paginationOptsValidator },
  handler: async (ctx, args) =>
    ctx.db.query("messages").withIndex("by_channel", (q) => q.eq("channel", args.channel)).order("desc").paginate(args.paginationOpts),
});

export const send = mutation({
  args: { channel: v.string(), body: v.string() },
  handler: async (ctx, args) => {
    const identity = await ctx.auth.getUserIdentity();
    if (identity === null) throw new Error("Not signed in");
    await ctx.db.insert("messages", {
      channel: args.channel,
      author: identity.name ?? identity.tokenIdentifier,
      body: args.body,
    });
  },
});

Step 4: Use it from React

import { useMutation, usePaginatedQuery } from "convex/react";
import { api } from "../convex/_generated/api";

export function Channel({ name }: { name: string }) {
  const { results, status, loadMore } = usePaginatedQuery(api.messages.list, { channel: name }, { initialNumItems: 25 });
  const send = useMutation(api.messages.send);
  return (
    <>
      {results.map((m) => <p key={m._id}>{m.author}: {m.body}</p>)}
      {status === "CanLoadMore" && <button onClick={() => loadMore(25)}>Older</button>}
      <button onClick={() => send({ channel: name, body: "deploy finished" })}>Post</button>
    </>
  );
}

Wrap the app in ConvexProvider with new ConvexReactClient(import.meta.env.VITE_CONVEX_URL). Use useQuery(api.x.y, args) for non-paginated reads, and useMutation(...).withOptimisticUpdate((localStore, args) => ...) to show a change before the server confirms.

Step 5: Auth, files, scheduling, search

Examples

Example 1: Real-time chat

User: "Create a real-time chat app with Convex and React."

Run npm create convex@latest, add the messages table, list and send from Steps 2 and 3, and the Channel component from Step 4. send throws "Not signed in" until an auth provider is configured (Step 5); to try the loop without one, drop the identity check and set author from an argument. Open the app in two browser windows: a message posted in one appears in the other without a refresh.

Example 2: Keyword search for support articles

User: "Add search over my articles table."

Add .searchIndex("search_body", { searchField: "body", filterFields: ["category"] }) to articles, then a query that calls withSearchIndex("search_body", (q) => q.search("body", term).eq("category", "billing")).take(20). The search query is reactive like any other. For semantic search, add a vectorIndex, create embeddings in an action, and call ctx.vectorSearch.

Guidelines

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.