Convex TypeScript/JavaScript SDK
repository·main·Indexed 43 days ago
https://github.com/get-convex/convex-jsA 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.
What's inside Convex
- 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.
How Convex AI Files removal works
mainThe
npx convex ai-files removecommand 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:- The CLI fetches the current skill list from
https://version.convex.dev/v1/agent_skills. - It attempts to remove every skill name returned by that catalog.
- It ignores local state files like
convex/_generated/ai/ai-files.state.json(specifically theinstalledSkillNamesfield). - 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.
- The CLI fetches the current skill list from
Understand the Server-side Interface-Implementation pattern
mainThe Convex server-side code follows an "interface-impl" pattern to balance developer type safety with internal implementation simplicity:
- Interfaces (Main Directory): The main directory contains interfaces that define the types for various abstractions. These interfaces are parameterized by the developer's
DataModeltype. 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. - Implementations (
impl/subdirectory): Theimpl/directory contains the actual logic. These implementations are not parameterized overDataModel. They use looser typing to simplify internal development, as the primary goal of theDataModeltype is to assist the end-user in writing correct code rather than validating the internal library structures.
- Interfaces (Main Directory): The main directory contains interfaces that define the types for various abstractions. These interfaces are parameterized by the developer's
Explore the Convex package structure
mainThe
convexpackage is modular, providing specific entry points depending on your application layer:- Backend: Use
convex/serverto define backend functions and database schemas. - React Applications: Use
convex/reactfor hooks and theConvexReactClient. - Browser/Generic Clients: Use
convex/browserfor theConvexHttpClientin non-React browser environments. - Data Utilities: Use
convex/valuesfor utilities related to values stored in Convex. - Authentication: Specialized React components are available for
convex/react-auth0(Auth0) andconvex/react-clerk(Clerk). - SSR/Frameworks: Use
convex/nextjsfor server-side helpers compatible with Next.js and other React frameworks. - CLI: The
convexcommand-line interface is used for managing Convex projects.
- Backend: Use
Create queries, mutations, and actions
mainConvex 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, andactionGeneric(or their shorthandquery,mutation, andactionexports 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 }); }, });Define a database schema with defineSchema and defineTable
mainConvex uses a schema definition to provide type safety for your database. Use
defineSchemato wrap your table definitions anddefineTableto define the structure of individual tables. You can also define indexes and search indexes directly within theTableDefinition.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"], }), });Verify AI Files installation paths
mainWhen running
npx convex ai-files installornpx 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 whenclaude-codeis configured.- Any other agent-specific paths defined in
aiFiles.skills.agents.
Note:
.cursor/skills/is not a default installation path. The default agents arecodexandclaude-code.You can check the current list of installed skills by running
npx convex ai-files statusafter installation.Override the Version API Origin
mainWhen 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_ORIGINenvironment variable. This is particularly useful during rollout windows when the local CLI expects a newer response shape from the/v1/agent_skillsendpoint than the deployed service currently provides.CONVEX_VERSION_API_ORIGIN=http://127.0.0.1:3212 npx convex ai-files removeConfigure preview deployments with `--preview-name` and `--preview-create`
mainWhen 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-branchDeploy to a production or preview deployment with `npx convex deploy`
mainUse the
npx convex deploycommand 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, usenpx convex devinstead.Deployment Target Selection
The target deployment is determined automatically based on your environment variables:
- Production: If
CONVEX_DEPLOYMENT_ENV_VAR_NAMEis set, it targets the project's default production deployment. - Preview: If
CONVEX_DEPLOY_KEY_ENV_VAR_NAMEis 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:- Run Command: If
--cmdis provided, it runs that command with the deployment URL available as an environment variable. - Typecheck: Runs typechecking on your Convex functions.
- Regenerate: Regenerates code in the
convex/_generateddirectory. - Bundle: Bundles functions and dependencies.
- Push: Pushes functions, indexes, and schema to the deployment.
- Preview Run: If deploying to a preview deployment and
--preview-runis specified, it executes that function.
npx convex deploy- Production: If
Convex CLI Node.js Version Requirements
mainThe 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.Configure Convex projects via CLI
mainThe
configurecommand (used internally bynpx convex devandnpx 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 likeCONVEX_DEPLOYMENTandCONVEX_URL, and ensures your local environment is correctly pointed to the intended deployment (cloud dev, cloud prod, or local).npx convex configure