Convex TypeScript/JavaScript SDK

repository·main·Indexed 43 days ago

https://github.com/get-convex/convex-js

A full-stack backend application platform providing a TypeScript/JavaScript SDK, client libraries, and CLI for building real-time, scalable applications. Version 1.46.0 includes tools for defining database schemas with defineSchema and defineTable, creating reactive queries, transactional mutations, and side-effect actions, as well as managing file storage, cron jobs, and authentication.

Tokens
18.2K
Snippets
59
Records
81
Agent score
57%

What's inside Convex

  1. Overview of Convex TypeScript/JavaScript SDKs

    main
    Convex provides a complete suite of TypeScript and JavaScript tools for building full-stack applications. This includes a backend SDK for defining logic and schemas, client libraries for various environments (React, Browser, Next.js), and a CLI for project management.
  2. How Convex AI Files removal works

    main

    The npx convex ai-files remove command does not rely on local tracking of installed skill names or their provenance. Instead, it uses the canonical version catalog as the single source of truth.

    When you run remove:

    1. The CLI fetches the current skill list from https://version.convex.dev/v1/agent_skills.
    2. It attempts to remove every skill name returned by that catalog.
    3. It ignores local state files like convex/_generated/ai/ai-files.state.json (specifically the installedSkillNames field).
    4. The operation is idempotent: if the catalog includes a skill that is not currently installed locally, the command still succeeds.

    This ensures that removal is driven entirely by the remote service, allowing for cleaner management of skills even if they were manually installed or if local state files are corrupted/outdated.

  3. Understand the Server-side Interface-Implementation pattern

    main

    The Convex server-side code follows an "interface-impl" pattern to balance developer type safety with internal implementation simplicity:

    1. Interfaces (Main Directory): The main directory contains interfaces that define the types for various abstractions. These interfaces are parameterized by the developer's DataModel type. This ensures that when you use these abstractions in your queries and mutations, you are guided by strict type safety based on your specific schema.
    2. Implementations (impl/ subdirectory): The impl/ directory contains the actual logic. These implementations are not parameterized over DataModel. They use looser typing to simplify internal development, as the primary goal of the DataModel type is to assist the end-user in writing correct code rather than validating the internal library structures.
  4. Explore the Convex package structure

    main

    The convex package is modular, providing specific entry points depending on your application layer:

    • Backend: Use convex/server to define backend functions and database schemas.
    • React Applications: Use convex/react for hooks and the ConvexReactClient.
    • Browser/Generic Clients: Use convex/browser for the ConvexHttpClient in non-React browser environments.
    • Data Utilities: Use convex/values for utilities related to values stored in Convex.
    • Authentication: Specialized React components are available for convex/react-auth0 (Auth0) and convex/react-clerk (Clerk).
    • SSR/Frameworks: Use convex/nextjs for server-side helpers compatible with Next.js and other React frameworks.
    • CLI: The convex command-line interface is used for managing Convex projects.
  5. Create queries, mutations, and actions

    main

    Convex functions are categorized into three types:

    • Queries: Read-only functions that fetch data. They are cached and reactive.
    • Mutations: Functions that modify data in the database. They are transactional.
    • Actions: Functions for side effects (e.g., calling external APIs, using non-deterministic logic). They cannot directly modify the database but can call mutations or queries.

    Use queryGeneric, mutationGeneric, and actionGeneric (or their shorthand query, mutation, and action exports in your environment) to define these functions.

    import { query, mutation, action } from "convex/server";
    
    export const myQuery = query({
      args: { name: v.string() },
      handler: async (ctx, args) => {
        return await ctx.db.query("users").filter(q => q.eq(q.field("name"), args.name)).collect();
      },
    });
    
    export const myMutation = mutation({
      args: { name: v.string() },
      handler: async (ctx, args) => {
        await ctx.db.insert("users", { name: args.name });
      },
    });
  6. Define a database schema with defineSchema and defineTable

    main

    Convex uses a schema definition to provide type safety for your database. Use defineSchema to wrap your table definitions and defineTable to define the structure of individual tables. You can also define indexes and search indexes directly within the TableDefinition.

    import { defineSchema, defineTable } from "convex/server";
    
    export default defineSchema({
      users: defineTable({
        name: v.string(),
        email: v.string(),
      }).index("by_email", ["email"]),
      posts: defineTable({
        authorId: v.id("users"),
        title: v.string(),
        body: v.string(),
      }).searchIndex("search_body", {
        searchField: "body",
        filterFields: ["authorId"],
      }),
    });
  7. Verify AI Files installation paths

    main

    When running npx convex ai-files install or npx convex ai-files update, the CLI writes skills to agent-native locations. Depending on your configuration, verify the following paths:

    • .agents/skills/: The canonical project-scoped installation path.
    • .claude/skills/: Symlinks for Claude Code when claude-code is configured.
    • Any other agent-specific paths defined in aiFiles.skills.agents.

    Note: .cursor/skills/ is not a default installation path. The default agents are codex and claude-code.

    You can check the current list of installed skills by running npx convex ai-files status after installation.

  8. Override the Version API Origin

    main

    When testing unreleased changes or working with a local stub of the version service, you can point the Convex CLI to a local endpoint using the CONVEX_VERSION_API_ORIGIN environment variable. This is particularly useful during rollout windows when the local CLI expects a newer response shape from the /v1/agent_skills endpoint than the deployed service currently provides.

    CONVEX_VERSION_API_ORIGIN=http://127.0.0.1:3212 npx convex ai-files remove
  9. Configure preview deployments with `--preview-name` and `--preview-create`

    main

    When using a preview deploy key (via CONVEX_DEPLOY_KEY), you can manage preview deployments using these flags:

    • --preview-name <name>: Associates the deployment with a specific name. In CI environments (Vercel, Netlify, Cloudflare Pages, GitHub), this defaults to the current Git branch name. If a deployment with that name already exists, it reuses it.
    • --preview-create <name>: Similar to --preview-name, but it deletes and recreates an existing preview deployment with the same name. This can only be used with a preview deploy key.

    Note: These two flags conflict and cannot be used together.

    npx convex deploy --preview-name my-feature-branch
    # Or to force a recreation:
    npx convex deploy --preview-create my-feature-branch
  10. Deploy to a production or preview deployment with `npx convex deploy`

    main

    Use the npx convex deploy command to push your Convex functions, indexes, and schema to a deployment. This command is intended for manual deployments or CI/CD pipelines. For local development, use npx convex dev instead.

    Deployment Target Selection

    The target deployment is determined automatically based on your environment variables:

    • Production: If CONVEX_DEPLOYMENT_ENV_VAR_NAME is set, it targets the project's default production deployment.
    • Preview: If CONVEX_DEPLOY_KEY_ENV_VAR_NAME is set (typical in CI), it targets the deployment associated with that key. If the key is a preview deploy key, it targets a preview deployment.

    Deployment Workflow

    When you run deploy, the CLI performs the following steps in order:

    1. Run Command: If --cmd is provided, it runs that command with the deployment URL available as an environment variable.
    2. Typecheck: Runs typechecking on your Convex functions.
    3. Regenerate: Regenerates code in the convex/_generated directory.
    4. Bundle: Bundles functions and dependencies.
    5. Push: Pushes functions, indexes, and schema to the deployment.
    6. Preview Run: If deploying to a preview deployment and --preview-run is specified, it executes that function.
    npx convex deploy
  11. Convex CLI Node.js Version Requirements

    main

    The Convex CLI requires a minimum Node.js version to function correctly.

    Requirements:

    • Node.js v20.0.0 or higher.

    If your current Node version is below this requirement, the CLI will exit with an error. It is recommended to use nvm (Node Version Manager) to manage and update your Node.js versions.

  12. Configure Convex projects via CLI

    main

    The configure command (used internally by npx convex dev and npx convex init) allows you to set up or switch between Convex projects. You can create a new project or link to an existing one. The configuration process manages environment variables like CONVEX_DEPLOYMENT and CONVEX_URL, and ensures your local environment is correctly pointed to the intended deployment (cloud dev, cloud prod, or local).

    npx convex configure