The complete guide to Convex

By

Updated

Tagged: Database

Learn Convex by building a real-time app with TypeScript, queries, mutations, authentication, indexes, search, file storage, background jobs, and tests.

Convex gives you a database, backend functions, and live updates through a single TypeScript API.

The flow is easy to picture. You write a backend function that reads data, your frontend subscribes to it, and whenever the underlying data changes, Convex reruns the function and pushes the new result to the browser.

That cuts out a lot of the usual plumbing. You can keep a task list in sync across browser tabs without polling, running a separate WebSocket server, or maintaining your own cache invalidation layer.

I use Convex across many of my projects, including the platforms behind my AI Workshop and Bootcamp courses. I also used it for my Astro membership starter, though that guide focuses on building one specific app. Here we’re going to learn Convex itself, from defining your first table to the things you need before shipping.

We’ll build a small task app with Astro and TypeScript. First we’ll put together a shared board so you can see live updates working right away, then we’ll add sign-in and turn it into a private per-user app. Using the same task model, we’ll also explore pagination, full-text search, attachments, scheduled work, and testing.

You don’t need React to follow along. The database and backend concepts work the same with any supported client, and I’ll point out where React’s hooks fit if that’s what you use.

The Convex homepage introduces its database and backend platform

Head over to the Convex website to create an account and open the dashboard.

Before you start

You’ll want to feel comfortable with JavaScript functions, objects, modules, and async / await.

If you want a refresher, my JavaScript Handbook covers those fundamentals, and my TypeScript Guide explains the types we’ll use for documents and function arguments.

Make sure you have npm and a current Node.js LTS release supported by Astro and Convex installed. You’ll also need a Convex account for the hosted development setup, plus a Clerk development application when we get to authentication.

I’m keeping the frontend small so our focus stays on Convex. The backend we build here works just as well from React, Vue, Svelte, a mobile app, or a plain HTTP client.

Our first shared board allows anonymous access on purpose so we can test live updates fast. Run it on a disposable development deployment with dummy tasks, and we’ll remove its public functions before anything goes live.

The Convex documentation with tutorials, quickstarts, and platform guides

The Convex documentation is handy to keep open alongside this guide, with quickstarts for different frontends and guides for each backend feature.

What Convex does

In a typical web app, you wire together a browser, an API server, and a database, with the API server checking permissions and turning database results into responses.

With Convex, you still write backend code, except it runs as Convex functions right alongside the database.

Your frontend calls those functions through the Convex SDK. Because Convex generates TypeScript types directly from your backend files, your editor knows every function’s arguments and return value as you work.

Out of the box, the platform also gives you scheduling, file storage, search, and integrations with auth providers, plus reusable backend packages called components.

Here is how a request moves from the browser to the database and back:

A Convex application's data pathA browser subscribes to a query. A mutation writes a transaction to the database, and Convex sends updated query results back to the browser. Actions call external services.SubscribeReadChange somethingAtomic writeRelevant data changedUpdated resultCall a mutationBrowserQuery functionConvex databaseMutation functionAction functionExternal API

Convex stores documents in tables. Each document looks like a regular JavaScript object with fields such as title, done, and owner.

There’s no SQL here. You query tables through Convex’s database API using indexes defined in your schema, and you model relationships with document IDs.

This setup shines when your app needs live shared state: dashboards, collaborative tools, task trackers, chat apps, and screens showing background-job progress.

The tradeoff is that you’re adopting Convex’s backend model, so existing SQL tools and database-specific extensions won’t carry over directly. We’ll revisit those tradeoffs once we’ve built the app.

Queries, mutations, and actions

Convex splits backend code into four function types based on what each one needs to do.

FunctionReads the database directlyWrites the database directlyCalls external APIsTypical use
QueryYesNoNoList tasks
MutationYesYesNoCreate or complete a task
ActionThrough queriesThrough mutationsYesSend an email or call an AI API
HTTP actionThrough queriesThrough mutationsYesReceive a webhook or serve an HTTP route

A query reads from a consistent database snapshot, and Convex tracks what it reads so subscribed clients automatically receive updates when the data changes.

When you need to write to the database, you use a mutation. Every mutation runs inside a transaction, so if it throws an error halfway through, Convex rolls back all of its database changes.

Talk to the outside world in an action instead. Actions can call fetch against external APIs and then invoke queries or mutations to read or save data, keeping network requests separate from database writes.

Finally, HTTP actions take a standard Request and return a Response. Use them when another service needs a URL to call, such as a webhook, or when you want to serve an HTTP route directly.

Keep those boundaries in mind as we build. If you catch yourself trying to call fetch inside a mutation or reaching for ctx.db inside an action, that work belongs in a different function type. The function overview covers all the supported combinations.

Create the project

We’ll start with an empty Astro project to handle our HTML and browser bundle, while Convex runs the database and backend functions.

Create the Astro project and install the Convex client:

npm create astro@latest convex-tasks -- --template minimal
cd convex-tasks
npm install convex

Accept the prompt to install dependencies if Astro asks, and keep TypeScript turned on.

Next, start Convex in its own terminal window:

npx convex dev

Follow the CLI prompts to sign in, create a project, and pick a hosted development deployment for this walkthrough.

Leave that command running while you work. It watches your convex/ directory, pushes backend changes as you save them, and regenerates your client types automatically.

Astro’s dev server runs separately, so start it in a second terminal:

npm run dev

The Convex CLI supports local development deployments too, though the hosted path lets us skip local backend setup while learning the API. Keep in mind that a hosted dev deployment is still reachable over the network, so keep real data off public test functions.

What the generated files are for

After initialization, your key files look like this (the exact generated filenames can shift slightly as the tooling evolves):

convex-tasks/
  convex/
    _generated/
      api.d.ts
      api.js
      dataModel.d.ts
      server.d.ts
      server.js
    tsconfig.json
  src/
    pages/
      index.astro
  .env.local
  package.json

Inside _generated/, api holds references to your public functions and internal holds references to backend-only internal functions. The generated server module exports query, mutation, and action typed for your schema, while dataModel provides helper types like Doc<'tasks'> and Id<'tasks'>.

Never edit files inside _generated/ by hand. Change your schema or backend functions and let the CLI regenerate them for you. You can see all the generated exports in the generated-code reference.

We’ll read process.env in our backend configuration, so let’s add Node’s TypeScript types:

npm install --save-dev @types/node

Then add "types": ["node"] inside compilerOptions in convex/tsconfig.json, keeping the other generated options intact. That gives TypeScript the declarations for process.env, while the Convex runtime still runs its own set of supported APIs.

Set the frontend URL

The CLI writes your deployment configuration to .env.local. Grab the development deployment’s client URL from the dashboard or the CLI output.

Add it to .env.local using Astro’s public environment-variable prefix so the browser can read it:

PUBLIC_CONVEX_URL=https://your-development-deployment.convex.cloud

Replace that placeholder with your deployment’s real URL, and leave the CLI’s existing variables untouched.

Your deployment URL is public configuration because the browser needs it to connect. A deploy key, an email-service API key, or a Clerk secret key is a different story: those carry private permissions and must stay strictly outside your browser bundles.

Restart Astro after changing .env.local, and make sure .env.local stays out of Git.

Define the database schema

A schema tells Convex which fields your documents hold and which indexes your queries can use.

We’ll define two tables here: demoTasks for our first anonymous board, and tasks for the authenticated app we’ll build later. Keeping them separate lets us drop the demo API later without having to untangle anonymous records from private user accounts.

Create convex/schema.ts with both tables:

import { defineSchema, defineTable } from 'convex/server'
import { v } from 'convex/values'

export default defineSchema({
  demoTasks: defineTable({
    title: v.string(),
    done: v.boolean(),
  }),
  tasks: defineTable({
    owner: v.string(),
    title: v.string(),
    done: v.boolean(),
    completedAt: v.optional(v.number()),
    attachmentId: v.optional(v.id('_storage')),
  })
    .index('by_owner', ['owner'])
    .index('by_owner_done', ['owner', 'done'])
    .searchIndex('search_title', {
      searchField: 'title',
      filterFields: ['owner'],
    }),
})

Save the file and watch the convex dev terminal to make sure it syncs cleanly. Fix any schema errors before moving on.

Convex automatically adds _id and _creationTime to every stored document, so you leave them out of defineTable. _id uniquely identifies the document, and _creationTime records when it was created in milliseconds, staying fixed even after you edit the document.

We’ll populate the owner string on the server from a verified user identity, never from an input field or a browser-supplied user ID.

Fields wrapped in v.optional(...) can be omitted from a document altogether. If a field needs to accept null explicitly, use a union validator such as v.union(v.string(), v.null()).

We’ll put the indexes to work in later chapters. For now, notice how your table fields, database indexes, and search indexes all live together in one file. See the schema documentation for other supported shapes.

The Bootcamp schema showing subscriptions, payments, and progress linked to users

Here’s part of the schema from my Bootcamp platform. The dashboard lays out the fields, indexes, and references between tables in one view.

Understand Convex values and IDs

TypeScript catches type mistakes while you write code, and Convex validates values again at runtime whenever a request arrives from the browser.

Here are the validators you’ll use most often:

ValidatorAccepted valueExample use
v.string()StringTask title
v.boolean()BooleanCompletion state
v.number()JavaScript numberTimestamp
v.int64()Signed 64-bit integer as a bigint64-bit integer values
v.id('tasks')ID for the named tableTask reference
v.array(v.string())Array of stringsBounded list of labels
v.object({ title: v.string() })Object matching a shapeNested structured data
v.optional(v.string())String or omitted fieldOptional note
v.union(v.literal('open'), v.literal('closed'))One of the allowed stringsStatus
v.null()nullExplicit empty value

Check the data-types reference whenever you pass values beyond standard JSON types. A Date, Map, or class instance isn’t stored natively, so convert dates to numeric timestamps or another supported representation first.

A table-specific ID gives TypeScript more information than a plain string:

import type { Id } from './_generated/dataModel'

const rememberTask = (id: Id<'tasks'>) => {
  console.log(id)
}

That import path works inside backend code under convex/. From src/, adjust the relative path to point to your _generated folder.

Validating v.id('tasks') confirms the argument belongs to the right table. Inside your function, you’ll still load the document to verify it exists and that the caller owns it.

Write your first query and mutations

For the shared board, you need four operations: list tasks, add a task, mark one done or open, and delete it. We’ll keep this first backend small. It returns the newest 50 tasks, validates titles, and rejects updates when a record is missing.

Create convex/demoTasks.ts with those four functions:

import { mutation, query } from './_generated/server'
import { ConvexError, v } from 'convex/values'

export const list = query({
  args: {},
  handler: async (ctx) => {
    return await ctx.db.query('demoTasks').order('desc').take(50)
  },
})

export const create = mutation({
  args: { title: v.string() },
  returns: v.id('demoTasks'),
  handler: async (ctx, args) => {
    const title = args.title.trim()
    if (title.length === 0 || title.length > 200) {
      throw new ConvexError('Use a title between 1 and 200 characters')
    }
    return await ctx.db.insert('demoTasks', { title, done: false })
  },
})

export const setDone = mutation({
  args: { id: v.id('demoTasks'), done: v.boolean() },
  returns: v.null(),
  handler: async (ctx, args) => {
    const task = await ctx.db.get(args.id)
    if (!task) throw new ConvexError('Task not found')
    await ctx.db.patch(args.id, { done: args.done })
    return null
  },
})

export const remove = mutation({
  args: { id: v.id('demoTasks') },
  returns: v.null(),
  handler: async (ctx, args) => {
    const task = await ctx.db.get(args.id)
    if (!task) throw new ConvexError('Task not found')
    await ctx.db.delete(args.id)
    return null
  },
})

Notice the ctx argument in each handler. Inside a query, ctx gives you read access to the database. Inside a mutation, it adds write methods too.

The args validators run before your handler executes, catching bad types right at the boundary. The title-length check lives inside the handler because it enforces your app’s own rule on top of the string type.

Convex turns your file path and export name into the API reference automatically. Because demoTasks.ts exports create, you call it as api.demoTasks.create.

One small detail in setDone: it takes the target boolean instead of acting like a toggle. If a user double-clicks or a network retry fires the request twice, sending “set done to true” twice leaves the task done. A toggle would flip it back and forth.

The Convex Functions panel listing the Bootcamp backend functions

Every deployed function shows up in the Functions panel. This screenshot is from the backend of my Bootcamp platform, which holds functions for authentication, course access, and student progress.

Runtime return validation

A few of the functions above also include a returns validator, which checks the shape of the value before it leaves the function.

You can write an explicit object validator for document lists too (including _id and _creationTime). I skipped that here and let TypeScript infer the document return types so we don’t have to repeat the schema in every snippet.

Keep args validators on your public functions either way. TypeScript catches mistakes while you write code, whereas args validators check live incoming requests at runtime. You can read more in the docs on argument and return-value validation.

Try the API from the terminal

As soon as convex dev finishes pushing those functions, you can call them straight from your terminal to create and list a task:

npx convex run demoTasks:create '{"title":"Read the Convex guide"}'
npx convex run demoTasks:list '{}'

The first command prints the new document’s ID. The second prints a list containing your task, its ID, and its creation time.

To inspect the stored rows visually, open the Convex dashboard:

npx convex dashboard

The dashboard lets you browse tables and run functions directly with admin privileges, which makes debugging fast. Normal calls from your frontend go through your public API with regular user permissions instead.

The Convex Data panel showing the Bootcamp progress table

Here’s the Data panel from my Bootcamp platform. Each row in the progress table tracks a week that a student has completed.

Build the shared board

Time to put a UI on top of those functions. We’ll stick to plain browser DOM APIs and Convex’s JavaScript client so there’s no framework hiding how the connection works.

Replace src/pages/index.astro with this page markup:

---
---

<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>Convex tasks</title>
  </head>
  <body>
    <main>
      <h1>Shared development board</h1>
      <p>Anonymous demo. Use invented tasks.</p>
      <form id="task-form">
        <label for="title">New task</label>
        <input id="title" name="title" required maxlength="200" />
        <button type="submit">Add task</button>
      </form>
      <p id="message" role="status" aria-live="polite">Connecting…</p>
      <ul id="tasks"></ul>
    </main>
    <script>
      import '../demo'
    </script>
  </body>
</html>

<style>
  body { font-family: system-ui, sans-serif; margin: 2rem auto; max-width: 42rem; padding: 0 1rem; }
  form, li { display: flex; flex-wrap: wrap; align-items: center; gap: 0.75rem; }
  li { margin: 0.75rem 0; }
  input[name='title'] { flex: 1; padding: 0.5rem; }
  button { padding: 0.5rem; }
  #message { min-height: 1.5rem; }
</style>

Importing the script this way lets Astro bundle the TypeScript file and its dependencies for the browser, instead of referencing node_modules directly from a script tag.

Next, create src/demo.ts to connect to Convex and wire up the form and task list:

import { ConvexClient } from 'convex/browser'
import { api } from '../convex/_generated/api'

const client = new ConvexClient(import.meta.env.PUBLIC_CONVEX_URL)
const form = document.querySelector<HTMLFormElement>('#task-form')!
const input = document.querySelector<HTMLInputElement>('#title')!
const list = document.querySelector<HTMLUListElement>('#tasks')!
const message = document.querySelector<HTMLParagraphElement>('#message')!
const submit = form.querySelector<HTMLButtonElement>('button')!

const showError = (error: unknown) => {
  console.error(error)
  message.textContent = 'The request failed. Check your connection and try again.'
}

const unsubscribe = client.onUpdate(api.demoTasks.list, {}, (tasks) => {
  list.replaceChildren()
  message.textContent = tasks.length ? '' : 'No tasks yet. Add your first task.'

  for (const task of tasks) {
    const item = document.createElement('li')
    const label = document.createElement('label')
    const checkbox = document.createElement('input')
    const text = document.createElement('span')
    const remove = document.createElement('button')

    checkbox.type = 'checkbox'
    checkbox.checked = task.done
    checkbox.addEventListener('change', async () => {
      checkbox.disabled = true
      try {
        await client.mutation(api.demoTasks.setDone, {
          id: task._id,
          done: checkbox.checked,
        })
      } catch (error) {
        checkbox.checked = task.done
        showError(error)
      } finally {
        checkbox.disabled = false
      }
    })

    text.textContent = task.title
    label.append(checkbox, ' ', text)
    remove.type = 'button'
    remove.textContent = 'Delete'
    remove.setAttribute('aria-label', `Delete ${task.title}`)
    remove.addEventListener('click', async () => {
      remove.disabled = true
      try {
        await client.mutation(api.demoTasks.remove, { id: task._id })
      } catch (error) {
        remove.disabled = false
        showError(error)
      }
    })

    item.append(label, remove)
    list.append(item)
  }
}, showError)

form.addEventListener('submit', async (event) => {
  event.preventDefault()
  const title = input.value.trim()
  if (!title) return
  submit.disabled = true
  try {
    await client.mutation(api.demoTasks.create, { title })
    input.value = ''
    input.focus()
  } catch (error) {
    showError(error)
  } finally {
    submit.disabled = false
  }
})

window.addEventListener('pagehide', () => {
  unsubscribe()
  void client.close()
}, { once: true })

We set each task title with textContent so any HTML characters stay plain text rather than rendering as markup.

This demo rebuilds the entire list whenever new data arrives, which works fine for 50 rows. Once a UI grows larger, you’ll want to update individual DOM nodes or let a framework handle reconciliation, since Convex takes care of syncing the data and leaves rendering up to your frontend.

Cleaning up the subscription on pagehide is enough for this single page. If your app uses client-side navigation or restores pages from the browser’s back-forward cache, hook into your router or page lifecycle so the subscription reconnects when the view comes back.

Check the behavior

Open your Astro URL in two browser tabs next to each other.

Add a task in the first tab and watch it appear in the second. Mark it complete in the second tab, and the first tab updates right away. Delete it, and both tabs clear it out.

Try the edge cases too. Delete every task to confirm the empty message shows up, then submit a title made only of spaces and verify nothing gets created.

To test that your backend guards the data on its own, send an invalid title straight from the terminal:

npx convex run demoTasks:create '{"title":"   "}'

The mutation fails and nothing is written to the database. Client-side form validation makes the UI nicer to use, while this backend check is what protects your data when someone bypasses the browser.

How real-time updates work

When you call client.onUpdate(), you subscribe to a query function along with its arguments.

Convex runs that query, keeps track of every piece of database data it touched, and sends back the result. Later, when a mutation modifies any of those dependencies, Convex reruns the query and pushes the fresh output to every subscriber.

Because you subscribe to a function result instead of a raw stream of table edits, your query can filter, join, and reshape documents before anything hits the client.

This flow shows what happens the moment another tab marks a task complete:

A task completion updates another browserBrowser A subscribes to the task list. Browser B calls setDone. After the transaction commits, Convex recomputes the subscribed result and sends it to A.Browser A subscribesto listConvex evaluatesqueryInitial task listreaches ABrowser B callssetDoneMutation reads andupdates taskTransaction commitsRelevant queryresult is recomputedBrowser A receivescompleted task

You can dig into the dependency tracking model in the real-time documentation.

Subscriptions sync your UI to the latest application state. If a field changes several times in quick succession, connected clients see the final value rather than every intermediate step. When you need a permanent record of every event, write explicit event documents into a table.

Convex also only reruns a query when stored data changes. If a query compares a deadline against Date.now(), nothing wakes it up when the clock ticks past that timestamp. Use a client timer for countdowns and display labels, and schedule a mutation when stored state needs to change at a deadline. We’ll build that pattern in the scheduling chapter.

Queries and HTTP requests

Use ConvexClient whenever you want live updates in the browser.

When you need a one-time read from a server route, a build script, or an HTTP handler, reach for ConvexHttpClient instead:

import { ConvexHttpClient } from 'convex/browser'
import { api } from './convex/_generated/api.js'

const client = new ConvexHttpClient(process.env.CONVEX_URL!)
const tasks = await client.query(api.demoTasks.list, {})
console.log(tasks)

Put that standalone script at the project root so the generated import path resolves cleanly, and run it with whatever TypeScript runner fits your setup.

An HTTP call fetches a single snapshot at that moment. If you run it during a static site build, your generated HTML bakes in whatever was in the database when the build ran.

With a static Astro page, the browser can open a ConvexClient subscription once the page loads. With server-rendered Astro, you can run a ConvexHttpClient query during the request to render initial HTML right away. If that server-rendered data is personalized, pass the authenticated user’s token and set proper cache headers so you never serve one user’s page to another.

Both clients are covered in the JavaScript client documentation.

What a mutation’s transaction guarantees

Every mutation runs inside a database transaction automatically. If a mutation inserts a task and logs an activity record, either both writes commit together or neither one does. You never have to open, commit, or roll back a transaction by hand.

Under the hood, Convex uses optimistic concurrency control. If two mutations collide on the same data, Convex can automatically retry one of them against the newer state. That’s why mutation code needs to stay deterministic within Convex’s supported runtime, so rerunning the handler produces a clean result.

Whenever you need to check a condition before writing, keep both steps in the same mutation. If you check the condition in a query and then fire a separate mutation later, another request can slip in between the two and change the data.

Picture a booking flow that checks for the last open seat and then reserves it. Show the seat count from a query in the UI, and verify availability again inside the reservation mutation before writing the booking. You can read how Convex handles conflicting reads and writes in the OCC and atomicity guide.

A transaction doesn’t include an external service

Convex’s transaction guarantee stops at its own database. An external API like a payment provider runs outside it.

If an action charges a customer’s card and the follow-up database write fails, the charge already went through on the provider’s side. Blindly retrying the whole action risks charging the card a second time.

To handle that safely, store an operation ID, pass an idempotency key to the provider, and build a way to reconcile uncertain results when a call times out. The exact workflow depends on the service you’re calling, and we’ll look at the database side of this pattern later in the guide.

Add authentication

The shared board got us familiar with Convex’s API, though right now any anonymous visitor can edit or wipe the list.

Next, we’ll build the private task app. Our tasks table already has an owner field and owner indexes ready to go, and every private function will pull the owner straight from a verified user identity.

Convex works out of the box with providers like Clerk, Auth0, and WorkOS, and Convex Auth is another option with its own setup. I’ll use Clerk’s JavaScript SDK here so our Astro frontend stays free of React.

No matter which provider you pick, the flow works the same way: the browser gets a signed token from the auth provider, Convex verifies that token, and your backend functions decide which data that user is allowed to touch.

Configure Clerk and Convex

Start by creating a development application in Clerk and turning on whichever sign-in methods you want to support.

In the Clerk dashboard, activate the Convex integration and copy your app’s Frontend API URL to use as the token issuer. Enabling that integration tells Clerk to add the convex audience to its session tokens. If Clerk moves a button or changes the dashboard wording, check the Convex and Clerk integration instructions.

Store that issuer URL as an environment variable on your development Convex deployment:

npx convex env set CLERK_JWT_ISSUER_DOMAIN https://your-clerk-instance.clerk.accounts.dev

Include the full issuer URL from Clerk, scheme and all. When you set up a custom domain or a production deployment later, you’ll configure its own issuer there too.

Now tell Convex to accept tokens from Clerk by creating convex/auth.config.ts:

import type { AuthConfig } from 'convex/server'

export default {
  providers: [
    {
      domain: process.env.CLERK_JWT_ISSUER_DOMAIN!,
      applicationID: 'convex',
    },
  ],
} satisfies AuthConfig

Save the file and let convex dev push the updated configuration.

Next, install Clerk’s browser SDK in your frontend project:

npm install @clerk/clerk-js @clerk/ui

Then add your Clerk publishable key to .env.local:

PUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_your_clerk_publishable_key

Swap in the real publishable key from your Clerk dashboard and restart Astro so it picks up the new environment variable.

You don’t need a Clerk secret key for this setup. The publishable key is meant to live in browser code, while secret keys stay strictly on the server.

Authentication and authorization are different checks

Authentication answers one question: who made this request? Authorization answers the next one: is this person allowed to read or change this specific task?

Being logged in only proves who you are, and hiding a Delete button in the UI only hides a button. Every private function needs both checks on the server before it reads or modifies a row.

Create a small helper in convex/lib/auth.ts to reuse across your private queries and mutations:

import { ConvexError } from 'convex/values'
import type { MutationCtx, QueryCtx } from '../_generated/server'
import type { Id } from '../_generated/dataModel'

export async function requireOwner(ctx: QueryCtx | MutationCtx) {
  const identity = await ctx.auth.getUserIdentity()
  if (!identity) throw new ConvexError('Sign in to continue')
  return identity.tokenIdentifier
}

export async function requireTask(
  ctx: QueryCtx | MutationCtx,
  id: Id<'tasks'>,
) {
  const owner = await requireOwner(ctx)
  const task = await ctx.db.get(id)
  if (!task || task.owner !== owner) {
    throw new ConvexError('Task not found')
  }
  return task
}

Using tokenIdentifier combines the issuer and the subject into one string, so you stay safe even if two different identity providers ever reuse the same subject ID.

Notice that we return an identical error whether a task is missing or belongs to someone else, so callers can’t probe IDs across accounts.

This helper expects a database-reading context (queries and mutations, while actions run authorization through a query or mutation). See the authentication-in-functions guide for everything on the identity object.

Build the private task API

With the auth helper ready, create convex/tasks.ts for the private task operations:

import { mutation, query } from './_generated/server'
import { ConvexError, v } from 'convex/values'
import { requireOwner, requireTask } from './lib/auth'

export const list = query({
  args: {},
  handler: async (ctx) => {
    const owner = await requireOwner(ctx)
    return await ctx.db
      .query('tasks')
      .withIndex('by_owner', (q) => q.eq('owner', owner))
      .order('desc')
      .take(50)
  },
})

export const create = mutation({
  args: { title: v.string() },
  returns: v.id('tasks'),
  handler: async (ctx, args) => {
    const owner = await requireOwner(ctx)
    const title = args.title.trim()
    if (title.length === 0 || title.length > 200) {
      throw new ConvexError('Use a title between 1 and 200 characters')
    }
    return await ctx.db.insert('tasks', { owner, title, done: false })
  },
})

export const setDone = mutation({
  args: { id: v.id('tasks'), done: v.boolean() },
  returns: v.null(),
  handler: async (ctx, args) => {
    const task = await requireTask(ctx, args.id)
    if (task.done === args.done) return null
    await ctx.db.patch(task._id, {
      done: args.done,
      completedAt: args.done ? Date.now() : undefined,
    })
    return null
  },
})

export const rename = mutation({
  args: { id: v.id('tasks'), title: v.string() },
  returns: v.null(),
  handler: async (ctx, args) => {
    await requireTask(ctx, args.id)
    const title = args.title.trim()
    if (title.length === 0 || title.length > 200) {
      throw new ConvexError('Use a title between 1 and 200 characters')
    }
    await ctx.db.patch(args.id, { title })
    return null
  },
})

export const remove = mutation({
  args: { id: v.id('tasks') },
  returns: v.null(),
  handler: async (ctx, args) => {
    const task = await requireTask(ctx, args.id)
    if (task.attachmentId) await ctx.storage.delete(task.attachmentId)
    await ctx.db.delete(task._id)
    return null
  },
})

In create, the owner field comes directly from the authenticated context, never from client arguments.

list queries through an owner index so Convex only scans the caller’s slice of tasks. For single-document edits (rename, setDone, and remove), each handler verifies that the caller owns that specific record before touching it.

When a user marks a task done, setDone saves a completion timestamp. Reopening the task clears completedAt by passing undefined in a patch, which is how you remove an optional field in Convex.

remove also cleans up the task’s file attachment if there is one. That builds on the one-file-per-task ownership setup we’ll wire up in the storage chapter.

Public and internal functions

Anything you export with query, mutation, or action is part of your public API. Anyone who knows its name can call it from outside, no matter how obscure the file path looks.

When a function should only be called by other backend code, define it with internalQuery, internalMutation, or internalAction. Convex exposes those under internal instead of api, so external clients can’t invoke them directly.

Still watch what your public functions pass into internal ones. If a public action accepts any task ID from the browser and forwards it straight to an internal delete mutation without checking ownership, you’ve accidentally turned that action into a public delete endpoint.

You can read more about splitting public and backend-only code in the internal-functions documentation.

Build the sign-in screen

Let’s put the private app on its own page at /private/. You can leave the shared board at / while you’re working through this guide, just remember to delete its backend functions before shipping a real app.

First, create src/pages/private.astro for the page markup:

---
---

<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>My Convex tasks</title>
  </head>
  <body>
    <main>
      <h1>My tasks</h1>
      <div id="sign-in"></div>
      <div id="user-button"></div>
      <p id="message" role="status" aria-live="polite">Loading sign-in…</p>
      <section id="workspace" hidden>
        <form id="task-form">
          <label for="title">New task</label>
          <input id="title" name="title" required maxlength="200" />
          <button type="submit">Add task</button>
        </form>
        <ul id="tasks"></ul>
      </section>
    </main>
    <script>
      import '../private'
    </script>
  </body>
</html>

<style>
  body { font-family: system-ui, sans-serif; margin: 2rem auto; max-width: 42rem; padding: 0 1rem; }
  form, li { display: flex; flex-wrap: wrap; align-items: center; gap: 0.75rem; }
  li { margin: 0.75rem 0; }
  input[name='title'] { flex: 1; padding: 0.5rem; }
  button { padding: 0.5rem; }
</style>

Then add the client logic in src/private.ts:

import { Clerk } from '@clerk/clerk-js'
import { ui } from '@clerk/ui'
import { ConvexClient } from 'convex/browser'
import { api } from '../convex/_generated/api'

const form = document.querySelector<HTMLFormElement>('#task-form')!
const input = document.querySelector<HTMLInputElement>('#title')!
const list = document.querySelector<HTMLUListElement>('#tasks')!
const workspace = document.querySelector<HTMLElement>('#workspace')!
const message = document.querySelector<HTMLParagraphElement>('#message')!
const signIn = document.querySelector<HTMLDivElement>('#sign-in')!
const userButton = document.querySelector<HTMLDivElement>('#user-button')!
const submit = form.querySelector<HTMLButtonElement>('button')!
const client = new ConvexClient(import.meta.env.PUBLIC_CONVEX_URL)
const clerk = new Clerk(import.meta.env.PUBLIC_CLERK_PUBLISHABLE_KEY)
let unsubscribe: (() => void) | undefined
let sessionId: string | null | undefined
let generation = 0

const showError = (error: unknown) => {
  console.error(error)
  message.textContent = 'The request failed. Please try again.'
}

function stopSubscription() {
  unsubscribe?.()
  unsubscribe = undefined
  list.replaceChildren()
  workspace.hidden = true
}

function subscribe() {
  if (unsubscribe) return
  unsubscribe = client.onUpdate(api.tasks.list, {}, (tasks) => {
    message.textContent = tasks.length ? '' : 'No tasks yet.'
    list.replaceChildren()
    for (const task of tasks) {
      const item = document.createElement('li')
      const label = document.createElement('label')
      const checkbox = document.createElement('input')
      const text = document.createElement('span')
      const remove = document.createElement('button')
      checkbox.type = 'checkbox'
      checkbox.checked = task.done
      checkbox.addEventListener('change', async () => {
        checkbox.disabled = true
        try {
          await client.mutation(api.tasks.setDone, {
            id: task._id,
            done: checkbox.checked,
          })
        } catch (error) {
          checkbox.checked = task.done
          showError(error)
        } finally {
          checkbox.disabled = false
        }
      })
      text.textContent = task.title
      label.append(checkbox, ' ', text)
      remove.type = 'button'
      remove.textContent = 'Delete'
      remove.setAttribute('aria-label', `Delete ${task.title}`)
      remove.addEventListener('click', async () => {
        remove.disabled = true
        try {
          await client.mutation(api.tasks.remove, { id: task._id })
        } catch (error) {
          remove.disabled = false
          showError(error)
        }
      })
      item.append(label, remove)
      list.append(item)
    }
  }, showError)
}

form.addEventListener('submit', async (event) => {
  event.preventDefault()
  const title = input.value.trim()
  if (!title) return
  submit.disabled = true
  try {
    await client.mutation(api.tasks.create, { title })
    input.value = ''
    input.focus()
  } catch (error) {
    showError(error)
  } finally {
    submit.disabled = false
  }
})

async function start() {
  await clerk.load({ ui })
  const removeListener = clerk.addListener(({ session }) => {
    const nextId = session?.id ?? null
    if (nextId === sessionId) return
    sessionId = nextId
    const current = ++generation
    stopSubscription()
    client.setAuth(async () => null)
    clerk.unmountSignIn(signIn)
    clerk.unmountUserButton(userButton)

    if (!session) {
      message.textContent = 'Sign in to see your tasks.'
      clerk.mountSignIn(signIn, {
        withSignUp: true,
        fallbackRedirectUrl: window.location.pathname,
        signUpFallbackRedirectUrl: window.location.pathname,
      })
      return
    }

    clerk.mountUserButton(userButton)
    message.textContent = 'Checking your session…'
    client.setAuth(
      async ({ forceRefreshToken }) => await clerk.session?.getToken({
        skipCache: forceRefreshToken,
      }) ?? null,
      (authenticated) => {
        if (current !== generation) return
        if (authenticated) {
          workspace.hidden = false
          subscribe()
        } else {
          stopSubscription()
          message.textContent = 'Could not verify your session. Sign in again.'
        }
      },
    )
  })

  window.addEventListener('pagehide', () => {
    removeListener()
    stopSubscription()
    void client.close()
  }, { once: true })
}

void start().catch(showError)

This file is longer than the backend because we’re wiring up the DOM by hand without a component framework.

Notice that the auth callback waits until Convex confirms the token before starting the task subscription. Clerk finishes signing the user in first, and Convex still needs a moment to verify that token on its end.

Whenever the session changes, we unsubscribe from the old query and clear the list from the page so a previous account’s tasks never stay visible after switching accounts. The generation counter handles the race condition where an auth callback from an older session resolves late.

This setup uses Clerk’s current Convex integration with standard session tokens. If you’re working with an older setup that uses a JWT template named convex, pass template: 'convex' to the token options here and in the attachment helper below.

The ui import gives us Clerk’s mounted sign-in and account widgets. Passing a callback to fetch tokens lets Convex ask Clerk for a fresh token whenever the current one expires, instead of grabbing a single token at startup and reusing it until it fails.

You can dig into Clerk’s mounted components and project settings in their JavaScript quickstart. For a bigger Astro site, you can use Clerk’s Astro integration to share auth UI and server helpers across pages.

Check private access

Open /private/, create an account, and add a task. Then open a second tab with the same account and make sure both tabs update together when you add or edit items.

Next, open a private window or another browser profile and sign in with a second account. You should see an empty task list.

Sign out and confirm that the tasks clear from the screen right away. Once you’re signed out, tasks.list and every task mutation should reject calls from that client.

We’ll turn these server-side checks into automated tests in the testing chapter. Still, testing with two real accounts is worth the minute it takes, because an app can look completely fine with a single user while leaking data between accounts.

Read data efficiently with indexes

An index groups documents by the fields you query together so Convex can jump straight to the rows you need.

Our by_owner index groups tasks by person, and by_owner_done groups them by owner first and completion status second. When multiple documents share the same indexed values, Convex orders them by creation time.

Add this query to convex/tasks.ts to pull only the current user’s open tasks:

export const open = query({
  args: {},
  handler: async (ctx) => {
    const owner = await requireOwner(ctx)
    return await ctx.db
      .query('tasks')
      .withIndex('by_owner_done', (q) =>
        q.eq('owner', owner).eq('done', false),
      )
      .order('desc')
      .take(50)
  },
})

The order of fields in an index matters a lot. With ['owner', 'done'], you can pick one owner and then narrow down to their open or completed tasks. If you later want every completed task across all users, you’ll want a separate index that starts with done.

Always build indexes around your real queries. “All my open tasks” and “every task completed yesterday across the whole app” hit the data differently and need different indexes.

The indexes guide goes deeper into equality prefixes and range conditions when you need more complex lookups.

Why filter is different

Convex also has a .filter() method, so in theory you could grab the tasks table and filter for the owner like this:

const tasks = await ctx.db
  .query('tasks')
  .filter((q) => q.eq(q.field('owner'), owner))
  .take(50)

This snippet assumes you’re inside a query handler where ctx and owner are already defined, just to contrast the API (keep using withIndex in the app).

The difference is how Convex finds the rows. Calling filter scans through documents and checks each one along the way, so Convex might read lots of other people’s tasks before collecting 50 matches for you.

Using withIndex narrows the search space before reading. That does less work per query, tracks fewer dependencies for reactivity, and makes concurrent writes less likely to collide with your transaction’s reads.

Indexes organize reads, and .unique() only checks that your query returned zero or one document. If you need a field to stay truly unique, query that index and insert the new document inside the same mutation.

Take a look at the query-performance guide when you’re deciding which indexes are worth adding to a table.

Avoid unbounded collect calls

Calling .collect() loads every matching document at once. That’s completely fine for a small list that you know will stay bounded.

A user’s task history grows over time, though. Use .take() when you want a fixed slice, and .paginate() when people need to browse further back.

Capping your queries helps the browser too. Fetching thousands of rows only to hide most of them in the UI still wastes bandwidth and makes the client do extra work.

Add cursor-based pagination

Right now our list only shows the newest 50 tasks. Anything older is still in the database, just unreachable from the screen.

Let’s add a paginated query so users can load more pages on demand. Convex hands back a cursor pointing to the end of the current page, and you send that cursor back on the next request to pick up where you left off.

Create convex/taskPages.ts with the paginated query:

import { paginationOptsValidator } from 'convex/server'
import { query } from './_generated/server'
import { requireOwner } from './lib/auth'

export const list = query({
  args: { paginationOpts: paginationOptsValidator },
  handler: async (ctx, args) => {
    const owner = await requireOwner(ctx)
    return await ctx.db
      .query('tasks')
      .withIndex('by_owner', (q) => q.eq('owner', owner))
      .order('desc')
      .paginate({ ...args.paginationOpts, numItems: 20 })
  },
})

Here we lock the page size on the server while spreading args.paginationOpts so Convex’s client helpers can still pass their own internal pagination options through.

Each response gives you page, continueCursor, and isDone. Pass continueCursor straight back to Convex as-is, without trying to parse it, build your own, or reuse it for another user’s query.

If you want to see the cursor flow in action, run these calls inside an authenticated client scope where client is already set up:

const first = await client.query(api.taskPages.list, {
  paginationOpts: { numItems: 20, cursor: null },
})

if (!first.isDone) {
  const next = await client.query(api.taskPages.list, {
    paginationOpts: { numItems: 20, cursor: first.continueCursor },
  })
  console.log(next.page)
}

These calls are one-time reads. They show how cursors step through pages, whereas a live paginated UI also has to deal with items being added or deleted while someone is scrolling.

If you’re using React, usePaginatedQuery handles those shifting page boundaries for you. With another frontend, reach for that integration’s pagination support, or build a snapshot-style browsing flow on purpose, because stitching together separate subscriptions can leave gaps when rows move between pages.

The pagination documentation explains how clients manage pages and how page splitting works on larger datasets.

Standard database indexes are built for exact matches and ranges. When you want to look up words inside text, you use a search index instead.

Our schema already defines search_title with an owner filter field, so we can search strictly inside the signed-in user’s task titles.

Create convex/taskSearch.ts to expose that search query:

import { query } from './_generated/server'
import { ConvexError, v } from 'convex/values'
import { requireOwner } from './lib/auth'

export const search = query({
  args: { text: v.string() },
  handler: async (ctx, args) => {
    const owner = await requireOwner(ctx)
    const text = args.text.trim()
    if (!text) return []
    if (text.length > 200) throw new ConvexError('Search text is too long')
    return await ctx.db
      .query('tasks')
      .withSearchIndex('search_title', (q) =>
        q.search('title', text).eq('owner', owner),
      )
      .take(20)
  },
})

Because the owner check runs inside the search index itself, Convex only returns the current user’s matches rather than sending other people’s data to the browser.

This is still a regular Convex query, which means you can subscribe to it just like the task list. If a matching task changes, the search results update automatically.

When you wire this up to a search input, keep a single active subscription for the current query string and unsubscribe from the previous one whenever the text changes. Adding a short debounce keeps you from firing off a new subscription on every keystroke.

Full-text search splits text into tokens and ranks matches, so it behaves differently from a plain title.includes(text) substring check or semantic search. Read through the full-text search documentation before promising specific substring, language, or ranking behavior in your UI.

Model relationships between tables

Say you decide later that tasks should belong to projects.

The cleanest way to model that is a separate projects table, with each task storing a projectId: v.id('projects') reference. Add an index starting with projectId on the tasks table so you can fetch all tasks for a project quickly.

Inside a query, you can load the related project with ctx.db.get(task.projectId). Convex tracks that read as part of the query’s dependencies, so if the project changes, any subscribed UI updates automatically.

When a mutation assigns a task to a project, verify that the project exists and that the caller has permission to use it. Convex validates the ID type through v.id('projects'), while access rules are up to your code.

Plan your deletion rules the same way. Decide whether deleting a project should remove its tasks, archive them, or reject the deletion, and write that logic in your mutation instead of expecting automatic relational cascades.

Keep growing collections in separate documents

Storing an array directly on a document works well for small, bounded lists like a handful of task labels.

For something that keeps growing, like a task’s comments, put each comment in its own document with a taskId index. Packing comments into an array on the task means rewriting a bigger parent document every time someone replies, and forcing readers of that task to download data they might not need.

Splitting them out also makes pagination straightforward, since you can query the first ten comments directly instead of fetching the entire array.

Shared projects need membership checks

Once multiple people collaborate on a project, checking a single owner field stops being enough.

A common pattern is a projectMembers table storing projectId, the user’s identity key, and their role. Before a mutation touches a project’s tasks, it looks up the caller’s membership record and checks that their role allows the action.

Always read that role from your projectMembers table on the server, never from a field passed in by the client.

An index on ['projectId', 'member'] keeps those permission checks fast. Make sure the mutations that create or update membership records run the same kind of check so only authorized users can invite people or change roles.

Call an external API with an action

Queries and mutations stay inside Convex’s database transactions. When you need to call an external service, you write an action.

Let’s start with a read-only request that fetches public repository details from GitHub. It gives us a working end-to-end action without needing an API key or paying for anything.

Create convex/github.ts:

import { action } from './_generated/server'
import { ConvexError, v } from 'convex/values'

export const convexRepository = action({
  args: {},
  returns: v.object({ name: v.string(), stars: v.number() }),
  handler: async (ctx) => {
    if (!await ctx.auth.getUserIdentity()) {
      throw new ConvexError('Sign in to continue')
    }
    const response = await fetch(
      'https://api.github.com/repos/get-convex/convex-backend',
      { headers: {
        Accept: 'application/vnd.github+json',
        'User-Agent': 'convex-tasks-tutorial',
      } },
    )
    if (!response.ok) throw new ConvexError('GitHub request failed')
    const data = await response.json()
    if (typeof data.full_name !== 'string' ||
        typeof data.stargazers_count !== 'number') {
      throw new ConvexError('Unexpected GitHub response')
    }
    return { name: data.full_name, stars: data.stargazers_count }
  },
})

You can then invoke it from an authenticated frontend handler like this:

const repository = await client.action(api.github.convexRepository, {})
console.log(repository.name, repository.stars)

Notice how the action validates the response fields it reads, since TypeScript types disappear at runtime and won’t catch surprises in third-party JSON.

GitHub can rate-limit unauthenticated requests, so a production version would usually add a server-side token, caching, and request limits. Put any API token in Convex’s deployment environment variables, never in a public frontend variable.

Actions run once when you call them and stay static even if the remote data changes later. If you want your UI to reflect an action’s progress or show its results live, save the state through mutations and subscribe to a query.

The actions documentation covers how actions call queries and mutations, along with the runtimes they support.

Actions that need Node.js

Convex’s default runtime already supports standard APIs like fetch, which covers a lot of ground. When an npm package depends on Node-specific APIs, put that action in its own file starting with 'use node' and keep your queries and mutations in separate files.

Stick with the default runtime whenever you can. Adding 'use node' switches the runtime so those packages work, while database access still goes through queries and mutations and network requests stay outside transactions.

Always await any async work you expect the action to complete. Kicking off a promise and returning early can cut the work short instead of running it as a durable background job.

Schedule background work

Once a user clicks a button, they might close the tab a second later. If the backend still needs to do work later on its own, save the request in a mutation and schedule an internal function from there.

Let’s build a small delayed reminder. It saves a reminder record right away and flips its status to ready when the time comes, while the frontend subscribes to that status. We’ll skip sending email for now since calling an external service adds its own failure modes, which we’ll look at next.

Add the reminders table inside defineSchema in convex/schema.ts, next to your existing tables:

reminders: defineTable({
  owner: v.string(),
  taskId: v.id('tasks'),
  status: v.union(v.literal('pending'), v.literal('ready')),
  dueAt: v.number(),
}).index('by_owner', ['owner']),

Now create convex/reminders.ts with the public mutation that schedules the reminder and the internal mutation that marks it ready:

import { internalMutation, mutation, query } from './_generated/server'
import { internal } from './_generated/api'
import { ConvexError, v } from 'convex/values'
import { requireOwner, requireTask } from './lib/auth'

export const schedule = mutation({
  args: { taskId: v.id('tasks'), delaySeconds: v.number() },
  returns: v.id('reminders'),
  handler: async (ctx, args) => {
    const task = await requireTask(ctx, args.taskId)
    if (!Number.isInteger(args.delaySeconds) ||
        args.delaySeconds < 1 || args.delaySeconds > 86400) {
      throw new ConvexError('Choose a delay from 1 second to 1 day')
    }
    const dueAt = Date.now() + args.delaySeconds * 1000
    const id = await ctx.db.insert('reminders', {
      owner: task.owner,
      taskId: task._id,
      status: 'pending',
      dueAt,
    })
    await ctx.scheduler.runAt(dueAt, internal.reminders.markReady, { id })
    return id
  },
})

export const markReady = internalMutation({
  args: { id: v.id('reminders') },
  returns: v.null(),
  handler: async (ctx, args) => {
    const reminder = await ctx.db.get(args.id)
    if (!reminder || reminder.status !== 'pending') return null
    const task = await ctx.db.get(reminder.taskId)
    if (!task || task.owner !== reminder.owner) {
      await ctx.db.delete(reminder._id)
      return null
    }
    await ctx.db.patch(reminder._id, { status: 'ready' })
    return null
  },
})

export const list = query({
  args: {},
  handler: async (ctx) => {
    const owner = await requireOwner(ctx)
    return await ctx.db
      .query('reminders')
      .withIndex('by_owner', (q) => q.eq('owner', owner))
      .order('desc')
      .take(20)
  },
})

Because the reminder record and the scheduled call happen in the same mutation, they commit together. If the mutation fails, you won’t be left with a saved reminder and no scheduled job behind it.

Scheduled functions run without the original caller’s auth context. That’s why the public mutation checks ownership first and stores the owner ID for the internal mutation to verify again when it fires (along with checking that the task still exists).

You can try it from authenticated client code using a task ID you got back from tasks.create:

const taskId = await client.mutation(api.tasks.create, {
  title: 'Take a short break',
})
await client.mutation(api.reminders.schedule, { taskId, delaySeconds: 30 })
const stop = client.onUpdate(api.reminders.list, {}, (reminders) => {
  console.log(reminders)
})

Remember to call stop() when the view goes away. Once the due time passes and the scheduler runs the job, you’ll see the reminder flip from pending to ready.

Scheduled mutations and scheduled actions differ

Scheduled mutations run with exactly-once execution inside Convex, and Convex automatically retries them on internal errors (a bug in your own code can still make one fail, of course).

Scheduled actions are different: they run at most once and Convex won’t retry them for you. If an action fails and the work still needs to happen, your app has to handle the retry.

Keep in mind that calling a third-party API from a scheduled job still has a gap between the two systems. The request can succeed on the provider’s side while your app fails before saving the result.

The scheduled-functions guide covers both execution models and the differences between scheduling from a mutation versus an action.

Design jobs that call external services

Sending an email or talking to an API needs more tracking than our in-database reminder.

A good job record stores the owner, an operation ID, a status, an attempt count, and the timestamp of the last attempt. If the provider gives you a request ID back, store that too.

The usual pattern is to let a public mutation check permissions, create the job document, and schedule an internal action. From there, the action calls internal mutations to claim and update the job around the external request, like this:

Record an external job before executing itAn authorized mutation saves a job and schedules an action. The action uses an idempotency key with the provider, then records success. An uncertain result is reconciled before another attempt.Known successUnknown resultAuthorized requestMutation savespending jobSchedule internalactionClaim attempt inmutationCall provider withstable operation keyRecord success inmutationRecord uncertainstateCheck providerbefore retrying

Reuse the same operation key every time you retry the same job. If you generate a fresh random key on each attempt, the provider treats every retry as a brand-new request.

Every runQuery and runMutation inside an action runs in its own transaction, so the database can change between calls. Write your state transitions with that in mind rather than assuming the row stayed untouched while the network call was in flight.

If you’re dealing with payments, adding an “uncertain” status helps a lot. When a call times out or errors halfway through, you mark the job uncertain and reconcile with the payment provider instead of charging the customer twice.

For longer multi-step jobs with retries, reach for a maintained workflow or work-pool component, while still deciding how your app handles duplicate requests and completed side effects.

Run recurring jobs with cron

Recurring jobs are handy for routine housekeeping, like clearing out old demo data.

Here we’ll cap each run at 100 old demo tasks so one cron execution never tries to sweep through a massive table all at once. Create convex/maintenance.ts:

import { internalMutation } from './_generated/server'
import { v } from 'convex/values'

export const removeOldDemoTasks = internalMutation({
  args: {},
  returns: v.number(),
  handler: async (ctx) => {
    const cutoff = Date.now() - 24 * 60 * 60 * 1000
    const tasks = await ctx.db
      .query('demoTasks')
      .withIndex('by_creation_time', (q) => q.lt('_creationTime', cutoff))
      .take(100)
    for (const task of tasks) await ctx.db.delete(task._id)
    return tasks.length
  },
})

Notice we didn’t have to add by_creation_time to the schema. Convex gives you that index automatically on every table.

Next, register the schedule in convex/crons.ts:

import { cronJobs } from 'convex/server'
import { internal } from './_generated/api'

const crons = cronJobs()
crons.interval('clean demo tasks', { hours: 1 }, internal.maintenance.removeOldDemoTasks)
export default crons

That uses a simple interval, and Convex also supports standard cron expressions when you want calendar-based schedules.

Cron expressions always run in UTC, which catches people out around daylight saving time: 09:00 UTC won’t stay 09:00 in Copenhagen all year. If your app promises reminders in the user’s local time, store their time zone and schedule the next timestamp yourself instead of relying on a fixed cron expression.

Convex also skips a scheduled run if the previous run of the same job is still going, so two runs never overlap. Read the cron jobs docs before relying on a cron schedule when exact delivery timing matters.

Store task attachments

Convex stores file bytes separately from your database documents, so a task only holds a reference ID pointing to its attachment.

Usually, direct uploads in Convex work in three steps:

  1. An authorized mutation generates an upload URL.
  2. The browser posts the file bytes to that URL.
  3. Another mutation saves the returned storage ID on the record.

There’s a subtle trap in step 3. A client can send back any storage ID, including a file someone else uploaded, and checking who owns the task won’t catch that.

For a small private app like ours, an authenticated HTTP upload endpoint is simpler and safer. The server checks task ownership, writes the file bytes to storage itself, and attaches the ID it just created. The browser never gets to pick a storage ID.

This works nicely for small files. If you need to handle large uploads, check the direct-upload documentation and pair it with an upload-session table that tracks ownership and cleans up unfinished uploads.

The Convex File Storage panel with no files uploaded

You can inspect uploaded files in the dashboard’s Files panel. My Bootcamp deployment doesn’t store files in Convex, so the view is empty here.

Add internal attachment functions

Create convex/files.ts for the internal queries and mutations our HTTP routes will call:

import { internalMutation, internalQuery } from './_generated/server'
import { ConvexError, v } from 'convex/values'

export const taskForOwner = internalQuery({
  args: { id: v.id('tasks'), owner: v.string() },
  handler: async (ctx, args) => {
    const task = await ctx.db.get(args.id)
    if (!task || task.owner !== args.owner) {
      throw new ConvexError('Task not found')
    }
    return task
  },
})

export const attach = internalMutation({
  args: {
    id: v.id('tasks'),
    owner: v.string(),
    storageId: v.id('_storage'),
  },
  returns: v.null(),
  handler: async (ctx, args) => {
    const task = await ctx.db.get(args.id)
    if (!task || task.owner !== args.owner) {
      throw new ConvexError('Task not found')
    }
    if (task.attachmentId) await ctx.storage.delete(task.attachmentId)
    await ctx.db.patch(task._id, { attachmentId: args.storageId })
    return null
  },
})

Because these functions are internal, they can trust the owner argument passed in by our HTTP action, which pulls it from the verified auth identity.

Notice that attach checks task ownership a second time. Between the first check and finishing the upload, the task could have been deleted or modified.

When you replace an attachment, the mutation deletes the old file right away. Since this app never shares a single storage ID across multiple tasks, removing the previous file won’t break anything else.

Write authenticated HTTP routes

Regular Convex SDK calls hit your deployment’s .convex.cloud URL. HTTP actions live on the .convex.site URL instead, which you can grab from the dashboard.

We’ll add two routes, one for uploading and one for downloading. Both require a bearer token and only allow browser CORS requests from the frontend origin we configure.

First, set your local frontend origin in Convex so it matches where Astro is running:

npx convex env set FRONTEND_ORIGIN http://localhost:4321

If Astro picked a different port on your machine, use that origin instead.

Now create convex/http.ts:

import { httpRouter } from 'convex/server'
import { httpAction } from './_generated/server'
import { internal } from './_generated/api'
import type { Id } from './_generated/dataModel'

const http = httpRouter()

function cors(request: Request) {
  const origin = request.headers.get('Origin')
  const allowed = process.env.FRONTEND_ORIGIN
  if (!allowed || origin !== allowed) return null
  return {
    'Access-Control-Allow-Origin': allowed,
    'Access-Control-Allow-Headers': 'Authorization, Content-Type',
    'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
    Vary: 'Origin',
  }
}

const preflight = httpAction(async (_ctx, request) => {
  const headers = cors(request)
  return new Response(null, { status: headers ? 204 : 403, headers: headers ?? {} })
})

http.route({ path: '/upload', method: 'OPTIONS', handler: preflight })
http.route({ path: '/attachment', method: 'OPTIONS', handler: preflight })

http.route({
  path: '/upload',
  method: 'POST',
  handler: httpAction(async (ctx, request) => {
    const headers = cors(request)
    if (!headers) return new Response('Origin not allowed', { status: 403 })
    const identity = await ctx.auth.getUserIdentity()
    if (!identity) return new Response('Unauthorized', { status: 401, headers })
    const id = new URL(request.url).searchParams.get('taskId')
    if (!id) return new Response('Missing taskId', { status: 400, headers })
    try {
      await ctx.runQuery(internal.files.taskForOwner, {
        id: id as Id<'tasks'>,
        owner: identity.tokenIdentifier,
      })
    } catch {
      return new Response('Task not found', { status: 404, headers })
    }
    const blob = await request.blob()
    if (blob.size === 0 || blob.size > 2 * 1024 * 1024) {
      return new Response('Use a file up to 2 MiB', { status: 400, headers })
    }
    if (blob.type !== 'text/plain') {
      return new Response('Use a plain text file', { status: 400, headers })
    }
    const storageId = await ctx.storage.store(blob)
    try {
      await ctx.runMutation(internal.files.attach, {
        id: id as Id<'tasks'>,
        owner: identity.tokenIdentifier,
        storageId,
      })
    } catch {
      await ctx.storage.delete(storageId)
      return new Response('Could not attach file', { status: 409, headers })
    }
    return new Response(null, { status: 204, headers })
  }),
})

http.route({
  path: '/attachment',
  method: 'GET',
  handler: httpAction(async (ctx, request) => {
    const headers = cors(request)
    if (!headers) return new Response('Origin not allowed', { status: 403 })
    const identity = await ctx.auth.getUserIdentity()
    if (!identity) return new Response('Unauthorized', { status: 401, headers })
    const id = new URL(request.url).searchParams.get('taskId')
    if (!id) return new Response('Missing taskId', { status: 400, headers })
    try {
      const task = await ctx.runQuery(internal.files.taskForOwner, {
        id: id as Id<'tasks'>,
        owner: identity.tokenIdentifier,
      })
      const blob = task.attachmentId ? await ctx.storage.get(task.attachmentId) : null
      if (!blob) return new Response('File not found', { status: 404, headers })
      return new Response(blob, {
        headers: {
          ...headers,
          'Content-Type': 'application/octet-stream',
          'Content-Disposition': 'attachment; filename="task-note.txt"',
          'Cache-Control': 'private, no-store',
          'X-Content-Type-Options': 'nosniff',
        },
      })
    } catch {
      return new Response('Task not found', { status: 404, headers })
    }
  }),
})

export default http

A few practical details worth keeping in mind here:

  • The as Id<'tasks'> cast only satisfies TypeScript. The internal function’s argument validator still checks the real ID at runtime.
  • CORS only controls which browser origins can read the response, since any non-browser client can send whatever Origin header it wants. The real security comes from the bearer token and the owner check.
  • Limiting uploads to text files keeps this example focused, though the MIME type comes from the client so you shouldn’t trust it on its own. Serving files as downloads with nosniff stops the browser from rendering an uploaded file as a web page on your .convex.site origin. If your app ever renders or parses user uploads, validate the real file contents for the formats you allow.
  • The size check runs after the request body is buffered in memory, so it acts as an app-level cap rather than streaming protection against massive payloads. Stay within Convex’s request limits, and switch to a dedicated upload flow when handling large files or untrusted traffic.
  • The cleanup block deletes the file if attaching fails, though a crash right between writing the bytes and attaching the ID can still leave an orphan file behind. For production, pair this with periodic cleanup or an explicit upload lifecycle.

Upload from the browser

Add your .convex.site origin to the frontend’s .env.local:

PUBLIC_CONVEX_SITE_URL=https://your-development-deployment.convex.site

Restart Astro, then create src/attachments.ts with the upload and download helpers:

import type { Clerk } from '@clerk/clerk-js'
import type { Id } from '../convex/_generated/dataModel'

async function token(clerk: Clerk) {
  const value = await clerk.session?.getToken()
  if (!value) throw new Error('Sign in to continue')
  return value
}

export async function uploadNote(clerk: Clerk, taskId: Id<'tasks'>, file: File) {
  const url = new URL('/upload', import.meta.env.PUBLIC_CONVEX_SITE_URL)
  url.searchParams.set('taskId', taskId)
  const response = await fetch(url, {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${await token(clerk)}`,
      'Content-Type': 'text/plain',
    },
    body: file,
  })
  if (!response.ok) throw new Error(await response.text())
}

export async function downloadNote(clerk: Clerk, taskId: Id<'tasks'>) {
  const url = new URL('/attachment', import.meta.env.PUBLIC_CONVEX_SITE_URL)
  url.searchParams.set('taskId', taskId)
  const response = await fetch(url, {
    headers: { Authorization: `Bearer ${await token(clerk)}` },
  })
  if (!response.ok) throw new Error(await response.text())
  const objectUrl = URL.createObjectURL(await response.blob())
  const link = document.createElement('a')
  link.href = objectUrl
  link.download = 'task-note.txt'
  link.click()
  window.setTimeout(() => URL.revokeObjectURL(objectUrl), 1000)
}

To wire those into the UI, add this import near the top of src/private.ts:

import { downloadNote, uploadNote } from './attachments'

Then inside subscribe(), drop this block right before item.append(label, remove):

const upload = document.createElement('input')
upload.type = 'file'
upload.accept = '.txt,text/plain'
upload.setAttribute('aria-label', `Attach a text note to ${task.title}`)
upload.addEventListener('change', async () => {
  const file = upload.files?.[0]
  if (!file) return
  upload.disabled = true
  try {
    await uploadNote(clerk, task._id, file)
    message.textContent = 'Note attached.'
  } catch (error) {
    showError(error)
  } finally {
    upload.disabled = false
  }
})
item.append(upload)

if (task.attachmentId) {
  const download = document.createElement('button')
  download.type = 'button'
  download.textContent = 'Download note'
  download.addEventListener('click', () => {
    void downloadNote(clerk, task._id).catch(showError)
  })
  item.append(download)
}

Once a file is attached, the reactive query delivers the updated attachmentId and the download button appears on its own.

Try uploading a small text file, replacing it with another one, downloading it, and deleting the task. While you’re testing, try requesting a missing file and hitting a task ID that belongs to a second user to verify both fail cleanly.

Private files and reusable URLs

ctx.storage.getUrl(storageId) gives you a direct download URL, which means anyone who gets hold of that link can download the file without hitting your ownership check again.

Since our HTTP route checks the bearer token on every download, keep those private files behind it and avoid exposing a separate public function that hands out direct URLs for them.

The file-serving guide compares direct URLs with serving files through HTTP actions.

Receive webhooks safely

HTTP actions also let you expose webhook endpoints for external services.

When you receive something like a payment webhook, verify the provider’s signature against the exact payload they signed. Hold off on parsing JSON until after verification if the signature check expects the raw text or raw bytes.

Once the signature checks out, hand off to an internal mutation that records the provider’s event ID and updates your app’s state in one transaction. An event table indexed on ['provider', 'eventId'] makes this clean: the mutation looks up that index, exits early if the event was already handled, and otherwise inserts the receipt and applies the change together.

Expect out-of-order deliveries too: a delayed webhook can overwrite newer state if applied blindly, so compare event timestamps or re-fetch the latest resource from the provider before updating your database.

Remember that the HTTP handler runs outside any database transaction, and checking the signature only proves who sent the request. Putting the receipt check inside the mutation is what keeps duplicate or replayed deliveries from running twice.

See the HTTP-actions documentation for routing and request details, or check my membership-site walkthrough to see how webhook handling fits into a full app.

Use Convex from React

Our Astro frontend uses the plain JavaScript client directly, while React gives you hooks that manage subscriptions automatically over those same api.tasks.list and api.tasks.create functions.

In an existing React app, install the Convex and Clerk React packages:

npm install convex @clerk/react

Wrap your app in ClerkProvider, then nest ConvexProviderWithClerk from convex/react-clerk inside it and pass Clerk’s useAuth hook. That wrapper handles fetching tokens and keeping auth state in sync (the plain ConvexProvider won’t hook Clerk up for you).

The Clerk integration guide has the complete provider setup for React and other frameworks.

Inside those providers, you can render a component that lists and creates private tasks. Save this as src/TaskList.tsx in your React app, adjusting the generated import path if your folders are laid out differently:

import { useState } from 'react'
import { useConvexAuth, useMutation, useQuery } from 'convex/react'
import { api } from '../convex/_generated/api'

export default function TaskList() {
  const { isAuthenticated, isLoading } = useConvexAuth()
  const tasks = useQuery(api.tasks.list, isAuthenticated ? {} : 'skip')
  const create = useMutation(api.tasks.create)
  const [title, setTitle] = useState('')
  const [pending, setPending] = useState(false)
  const [error, setError] = useState('')

  if (isLoading) return <p>Checking your session…</p>
  if (!isAuthenticated) return <p>Sign in to see your tasks.</p>
  if (tasks === undefined) return <p>Loading tasks…</p>

  return (
    <section>
      <form onSubmit={async (event) => {
        event.preventDefault()
        if (!title.trim()) return
        setPending(true)
        setError('')
        try {
          await create({ title: title.trim() })
          setTitle('')
        } catch {
          setError('Could not create the task. Please try again.')
        } finally {
          setPending(false)
        }
      }}>
        <label>
          New task
          <input value={title} onChange={(event) => setTitle(event.target.value)}
            required maxLength={200} />
        </label>
        <button disabled={pending}>Add task</button>
      </form>
      <p role="status">{error}</p>
      {tasks.length === 0 ? <p>No tasks yet.</p> : (
        <ul>{tasks.map((task) => <li key={task._id}>{task.title}</li>)}</ul>
      )}
    </section>
  )
}

One detail to watch: useQuery returns undefined while the initial data is still loading, and an empty array once the query finishes with zero tasks. Render separate loading and empty states for those two cases.

Passing 'skip' keeps the private query from running before Convex auth is ready.

If a query throws an error, catch it with a React error boundary. Mutation errors happen inside your event handlers, so you can catch them right there and show a message in the UI.

When you need pagination, reach for usePaginatedQuery(api.taskPages.list, {}, { initialNumItems: 20 }). It gives you results, status, and loadMore, so you can show a Load More button whenever status tells you there’s another page to fetch.

Optimistic updates

If you want a click to feel instant while the mutation is still in flight, React supports optimistic updates through useMutation(...).withOptimisticUpdate(...). It patches the local query cache right away, then replaces it with the server’s real result once the mutation finishes (or rolls back if it fails).

For tasks.setDone, you can find the task inside api.tasks.list and flip its done flag in the cache. If your screen also shows an open-only list, search results, or a count badge, remember to update those cached queries too so the UI stays consistent.

Start with regular reactive mutations first. Add optimistic updates only for interactions that genuinely need instant feedback, and test how they roll back on failure. The server database always has the final say, especially for permissions, balances, and reservations.

You can check the cache API in the optimistic-updates guide.

Full-text search looks for matching words. Vector search looks for nearby numeric representations (usually embeddings of text or images) so you can match by meaning instead.

In our task app, semantic search could connect “prepare the talk” with “finish conference slides” even though they share no words.

To set it up, you store an embedding field on your documents (or in a separate embeddings table), generate those vectors through an external model, and define a vector index whose dimensions match that model. Stick to one embedding model and keep your preprocessing consistent. Vectors from different models live in completely different spaces, even when they have the same length.

In Convex, vector search runs inside actions through ctx.vectorSearch. That call gives you back document IDs and similarity scores, and then you run a query to fetch the matching application data. Because it runs in an action on demand rather than as a reactive query, the usual pattern is to trigger the search when the user asks for it, then subscribe to the returned documents separately if you care about live updates.

Keep permissions in the search path

Add an owner or workspace filter field to your vector index so every search stays scoped to what the caller is allowed to see.

Then check permissions again when you fetch the full documents. Between the vector search and the follow-up query, a record could be deleted, moved, or have its access changed. When you’re working with private data, always verify access on the fetched record regardless of its similarity score. The vector-search guide shows the index definition and action API.

My advice is to hold off on vector search until regular full-text search stops cutting it. Task titles are short, and keyword search often does everything you need.

Add backend components

A Convex component is a reusable backend package that brings its own functions and data model. Components cover common building blocks like workflow execution, rate limiting, and aggregation, saving you from writing and maintaining that plumbing yourself.

Adding one usually means installing its npm package, registering it in convex/convex.config.ts with defineApp() and app.use(...), and calling its generated references or wrapper API. Follow each component’s own setup docs, since initialization steps and function names differ from package to package.

A component keeps its tables isolated from yours, so your app talks to it through its public API instead of reading its database directly. Your own functions still handle authorization before calling into it. Check that the caller owns the task before hitting a rate limiter, and verify their permissions before kicking off a workflow export.

The components guide covers registration and boundaries in detail. For our task app, the built-in scheduler already handles our reminders.

Test the backend

Authorization is worth testing automatically. Hiding someone else’s tasks in the UI is nice, but if a mutation still accepts any task ID, a direct request can slip right past it.

We’ll use Vitest and convex-test to run our backend functions against a mock Convex environment. Start by installing the test dependencies:

npm install --save-dev convex-test vitest @edge-runtime/vm

Next, create vitest.config.ts at the project root so Vitest knows how to run the suite:

import { defineConfig } from 'vitest/config'

export default defineConfig({
  test: {
    environment: 'edge-runtime',
    include: ['convex/**/*.test.ts'],
  },
})

Now add convex/tasks.test.ts with the backend tests:

/// <reference types="vite/client" />

import { convexTest } from 'convex-test'
import { expect, test } from 'vitest'
import { api } from './_generated/api'
import schema from './schema'

const modules = import.meta.glob('./**/*.ts')
const identity = (subject: string) => ({
  issuer: 'https://auth.flaviocopes.com',
  subject,
})

test('signed-out requests cannot list or create private tasks', async () => {
  const t = convexTest(schema, modules)
  await expect(t.query(api.tasks.list, {})).rejects.toThrow()
  await expect(t.mutation(api.tasks.create, { title: 'Private' })).rejects.toThrow()
})

test('an owner can create, rename, complete, reopen, and delete a task', async () => {
  const t = convexTest(schema, modules)
  const alice = t.withIdentity(identity('alice'))
  const id = await alice.mutation(api.tasks.create, { title: ' Read the docs ' })
  expect((await alice.query(api.tasks.list, {}))[0].title).toBe('Read the docs')
  await alice.mutation(api.tasks.rename, { id, title: 'Try the example' })
  await alice.mutation(api.tasks.setDone, { id, done: true })
  let task = (await alice.query(api.tasks.list, {}))[0]
  expect(task.done).toBe(true)
  expect(task.completedAt).toBeTypeOf('number')
  await alice.mutation(api.tasks.setDone, { id, done: false })
  task = (await alice.query(api.tasks.list, {}))[0]
  expect(task.completedAt).toBeUndefined()
  await alice.mutation(api.tasks.remove, { id })
  expect(await alice.query(api.tasks.list, {})).toEqual([])
})

test('another user cannot see or change the task', async () => {
  const t = convexTest(schema, modules)
  const alice = t.withIdentity(identity('alice'))
  const bob = t.withIdentity(identity('bob'))
  const id = await alice.mutation(api.tasks.create, { title: 'Alice only' })
  expect(await bob.query(api.tasks.list, {})).toEqual([])
  await expect(bob.mutation(api.tasks.setDone, { id, done: true })).rejects.toThrow()
  await expect(bob.mutation(api.tasks.rename, { id, title: 'Taken over' })).rejects.toThrow()
  await expect(bob.mutation(api.tasks.remove, { id })).rejects.toThrow()
  expect((await alice.query(api.tasks.list, {}))[0].title).toBe('Alice only')
})

test('invalid titles fail without creating records', async () => {
  const t = convexTest(schema, modules)
  const alice = t.withIdentity(identity('alice'))
  await expect(alice.mutation(api.tasks.create, { title: '   ' })).rejects.toThrow()
  await expect(alice.mutation(api.tasks.create, { title: 'a'.repeat(201) })).rejects.toThrow()
  expect(await alice.query(api.tasks.list, {})).toEqual([])
})

test('repeating setDone preserves the completed state and timestamp', async () => {
  const t = convexTest(schema, modules)
  const alice = t.withIdentity(identity('alice'))
  const id = await alice.mutation(api.tasks.create, { title: 'Finish tests' })
  await alice.mutation(api.tasks.setDone, { id, done: true })
  const before = (await alice.query(api.tasks.list, {}))[0]
  await alice.mutation(api.tasks.setDone, { id, done: true })
  const after = (await alice.query(api.tasks.list, {}))[0]
  expect(after.done).toBe(true)
  expect(after.completedAt).toBe(before.completedAt)
})

test('a deleted task cannot be updated', async () => {
  const t = convexTest(schema, modules)
  const alice = t.withIdentity(identity('alice'))
  const id = await alice.mutation(api.tasks.create, { title: 'Temporary' })
  await alice.mutation(api.tasks.remove, { id })
  await expect(alice.mutation(api.tasks.setDone, { id, done: true })).rejects.toThrow()
})

test('search is restricted to the caller', async () => {
  const t = convexTest(schema, modules)
  const alice = t.withIdentity(identity('alice'))
  const bob = t.withIdentity(identity('bob'))
  await alice.mutation(api.tasks.create, { title: 'Convex notes' })
  await bob.mutation(api.tasks.create, { title: 'Convex practice' })
  const results = await alice.query(api.taskSearch.search, { text: 'Convex' })
  expect(results.map((task) => task.title)).toEqual(['Convex notes'])
})

test('pagination does not include another user', async () => {
  const t = convexTest(schema, modules)
  const alice = t.withIdentity(identity('alice'))
  const bob = t.withIdentity(identity('bob'))
  await alice.mutation(api.tasks.create, { title: 'Alice task' })
  await bob.mutation(api.tasks.create, { title: 'Bob task' })
  const result = await alice.query(api.taskPages.list, {
    paginationOpts: { numItems: 20, cursor: null },
  })
  expect(result.page.map((task) => task.title)).toEqual(['Alice task'])
  expect(result.isDone).toBe(true)
})

The vite/client reference gives TypeScript types for import.meta.glob in this file, and Convex’s generated backend TypeScript config also type-checks files under convex/.

Run the tests with:

npx vitest run

The fake identities here are great for testing your function logic and access checks fast. Pair them with a real development backend and browser tests to exercise Clerk’s token issuance and Convex’s live JWT verification end to end. The testing documentation covers what the mock handles, including tools for testing scheduled functions.

What to test beyond CRUD

Once basic reads and writes are covered, test the trickier paths too:

  • For reminders, make sure a caller can’t schedule a reminder on someone else’s task, verify that deleted tasks are handled cleanly, and check that a scheduled reminder reaches its expected final state.
  • For attachments, test signed-out requests, cross-user IDs, invalid IDs, empty files, oversized files, and replacing or deleting files. Also check CORS preflight requests from your deployed frontend origin.
  • For webhooks, test duplicate deliveries and out-of-order events. For external jobs, simulate the provider succeeding while your database update fails.

Handle errors without losing useful state

A failed query, a failed mutation, and a dropped connection each call for a different reaction in the UI.

When a query fails, the page can’t render the data it asked for, so show an error state or an error boundary with a clear way to recover. When a mutation fails, keep whatever the user typed so they can fix it or try again. That’s why our create handlers only clear the input after a request succeeds.

A dropped connection leaves whatever data you already loaded sitting on screen, so decide how loudly to flag that it might be stale. A task manager can keep the list visible with a reconnecting notice, while a financial flow probably wants to pause actions until the connection comes back.

The Convex SDK takes care of reconnecting automatically. If you want a full offline-first app with persistent local storage and conflict resolution, plan to design that layer separately.

Application errors and unexpected failures

Use ConvexError when you want to send something useful to the frontend, like a validation message or a structured application error code.

Keep secrets and other people’s records out of error messages. On the backend, log enough context to debug what happened without dumping credentials or private request bodies.

Unexpected exceptions belong in your monitoring so you can investigate them. Swallowing every failure and returning “task not found” hides the difference between a permission check and an outage. Our compact HTTP example returns generic errors to the client, so in production you’ll want to record clean diagnostic logs on the server alongside them.

Check the error-handling guide for how Convex passes errors back to clients.

Evolve the schema without breaking the app

If you add a required field to a table that already has rows, schema validation can fail because older documents lack that field.

Instead, roll out changes that affect existing data in stages:

  1. Add the new field as optional, and make readers handle missing values.
  2. Update writers so new and edited documents populate it.
  3. Backfill older documents in bounded batches.
  4. Verify the backfill finished cleanly, then switch the field to required.

Say we add a priority field. New tasks can start writing priority: 'normal' while older tasks fall back to 'normal' when rendered. Once every document has a valid priority, tighten the validator.

Renaming a field takes the same care. People with open browser tabs can keep running your previous frontend right after you deploy the backend, so keep old argument names and return shapes working during the transition where needed.

Indexes on large tables need a little planning too. A new index has to backfill before queries can use it, and dropping an index that a live function still queries will break that path. Use Convex’s staged-index features when your dataset gets big enough for that to matter.

Keep backfills bounded

A single mutation that tries to rewrite an entire database can hit read, write, or execution limits.

Work through one batch at a time, save your progress, and schedule the next batch. Write the backfill so it’s safe to resume and safe to run again if needed.

Before any destructive migration on important data, take an export or backup, and test the restore path too so you know you can recover from it.

See backup and restore for the options Convex supports.

Keep development and production separate

Your development deployment has its own database and backend environment, completely separate from production.

Clerk works the same way: your production Clerk app has its own keys and settings. Put your production Clerk issuer on the production Convex deployment, and use the matching production publishable key in your production frontend.

Before you deploy, map out every environment variable and where it lives:

VariableUsed byPublic?Purpose
PUBLIC_CONVEX_URLAstro browser bundleYesSDK deployment URL
PUBLIC_CONVEX_SITE_URLAstro browser bundleYesHTTP-action origin
PUBLIC_CLERK_PUBLISHABLE_KEYAstro browser bundleYesClerk frontend configuration
CLERK_JWT_ISSUER_DOMAINConvex auth configYes, but configured on backendTrusted token issuer
FRONTEND_ORIGINConvex HTTP routesYes, but configured on backendBrowser CORS allowlist
CONVEX_DEPLOY_KEYTrusted deployment processNoPermission to deploy backend code
Provider API keysConvex actionsNoAccess to external services

Astro bakes PUBLIC_ variables into the static bundle at build time. If you change one in your hosting dashboard, rebuild the site so the updated value makes it into the bundle.

Put backend secrets like email API keys on the Convex deployment that runs the action. Variables set on your frontend host stay on the frontend host and won’t reach Convex actions.

The environment-variable documentation covers how to manage values per deployment.

Deploy the application

Your frontend and your Convex backend deploy separately. For this static Astro app, you can host the frontend on Cloudflare Pages while the database and functions run on Convex.

Before shipping, remove convex/demoTasks.ts, src/demo.ts, and the anonymous page in src/pages/index.astro, then use the private page as your app’s home page (only updating its script import if its relative path changes). You can leave the old demo data in its unused dev table or clean it up, just make sure you remove the backend demo files too so those public functions are no longer callable.

Deploy the backend

Configure your production Convex environment through the dashboard or the CLI using your real production issuer and frontend origin:

npx convex env set --prod CLERK_JWT_ISSUER_DOMAIN https://clerk.your-production-domain.com
npx convex env set --prod FRONTEND_ORIGIN https://your-app.pages.dev
npx convex deploy

Swap those placeholder origins for your real production values. If you use a custom frontend domain, use that origin instead of the pages.dev one.

Check the deployment output and the Convex dashboard to grab the right production URL, since it will be different from your development URL.

Deploy the frontend

Connect your repository in Cloudflare Pages and configure these settings:

SettingValue
Build commandnpm run build
Output directorydist
PUBLIC_CONVEX_URLProduction Convex SDK URL
PUBLIC_CONVEX_SITE_URLProduction Convex HTTP-action URL
PUBLIC_CLERK_PUBLISHABLE_KEYProduction Clerk publishable key

Allow your production frontend domain in your Clerk application settings.

Cloudflare’s Astro deployment guide covers the Pages setup. Because this example outputs static files, you don’t need an SSR adapter (server-rendered Astro routes need a different hosting setup).

For automated deployments, Convex can run your frontend build through convex deploy --cmd ... and pass the deployment URL straight into the build. Follow the custom-hosting guide to keep your backend deploy and frontend bundle pointed at the same environment.

Keep deploy keys inside your trusted CI environment, and never put a deploy key in a PUBLIC_ variable.

Check the deployed flow

Once everything is live, run through the app in production with a couple of test accounts:

  • Create a task with your first test account, open a second tab to confirm live updates work, then sign in with a second account to verify isolation.
  • Upload and download a text note from the deployed origin, and check that a signed-out download fails and another user’s task ID gets rejected.
  • Schedule a reminder and watch it become ready while inspecting function logs and scheduled-function status in the dashboard.
  • Call the removed demo API to confirm the old anonymous mutation is gone.

Understand usage, costs, and limits

What a query costs comes down to how much work it does and how often it runs. Fetching a handful of rows through an index is cheap, while scanning a big table on every keystroke adds up fast.

Keep an eye on database reads and writes, function execution time, bandwidth, file storage, and how often your live subscriptions re-run. If your actions call external services, those have their own bills too.

For a busy dashboard, look at how many queries each screen subscribes to, how much data they send back, and which writes cause them to re-run.

Take a derived count that scans every task whenever something changes. It works fine in a tiny app, then gets expensive as the table grows. Once you hit that point, switch to a maintained aggregate or an aggregation component so the count stays accurate inside transactions without scanning the whole table.

Convex also puts limits on individual functions and operations, not just on your monthly plan. Never write a job assuming it can load every document into memory or run forever.

Check the pricing page and the limits reference against your workload. Spin up a representative test deployment to measure your real numbers instead of building around the free tier.

The Bootcamp production deployment Health panel with function calls, failures, and cache hits

The Health panel gives you a quick snapshot of how a deployment is doing. Here’s my Bootcamp production deployment, showing function calls, failure rate, and query cache hits.

Debug common problems

SymptomWhat to check
api.tasks is missing from generated typesMake sure the function file exports it and convex dev finished without errors
Frontend connects but shows the wrong dataCheck which deployment URL was baked into the frontend build
Signed-in user gets an unauthenticated errorCheck your issuer, audience, token setup, and whether Convex auth finished loading
One user can edit another user’s taskCheck the record ownership check inside the backend mutation
HTTP route returns 404Make sure you’re hitting the HTTP-action URL and check the path and method in convex/http.ts
Upload works locally but fails in productionCheck the production origin, CORS preflight, bearer token, and deployment variables
Query gets slow as data growsCheck the index range, scan size, returned data, and any unbounded collections
Time-based state never changesPassing a deadline writes nothing to the database; schedule a mutation or drive it with a display timer
Scheduled function can’t find a userScheduled work doesn’t carry auth context; pass or read authorized stored context instead
An external job ran but looks unfinishedReconcile the provider’s result before you retry the side effect
Schema upload fails after adding a fieldExisting documents may not match the new validator

Start with the deployment URL and the function logs. Often, what looks like a frontend bug is the app pointing at the wrong deployment or a request getting rejected on the backend.

When you’re debugging authentication, inspect only the token claims you need. Never paste full bearer tokens into logs or support messages.

Convex execution logs for the Bootcamp platform with a query selected

Click any execution in the Logs panel to see how long it ran and what resources it used. This one is a session lookup from my Bootcamp platform.

How I would use Convex

I use Convex in many of my projects, including the platforms behind my AI Workshop and Bootcamp courses. It fits apps where several screens show the same live state and you want to keep your backend logic in TypeScript.

A small team dashboard, a task manager, or an app showing background-job progress fits that pattern well. For a new app like that, start with indexed queries and plain mutations. Wire up authentication before any real user data goes in, and bring in actions only when you need to talk to the outside world.

You don’t have to put the Convex browser client on every page either. The membership starter takes a different route: Astro owns the HTTP layer, and Convex stores the membership data behind it.

For a mostly static site, pause and ask whether you need an application database at all. A reactive backend doesn’t add much to a page whose content only changes when you publish a new article.

Weigh the operational model against your team’s existing skills too. If an app is already built around PostgreSQL, SQL reporting, and a large relational schema, moving it comes with a real migration cost.

Where Convex may be a poor fit

Once you build on Convex, its database API and function runtime become part of your application architecture, so review the trade-offs early.

If your main workload is ad hoc SQL analytics, you’re better off with a database and reporting stack built around SQL. Same goes if you need a specific PostgreSQL extension, since Convex queries run against its own document API rather than Postgres SQL.

Apps that have to stay offline for days and reconcile lots of conflicting edits need their own design. A reconnecting live client handles short drops well, but persistent offline storage and merge rules are still yours to plan and test.

If you have strict infrastructure, regional, compliance, or recovery requirements, check what hosting and operational options are supported before you commit. You can self-host Convex if you need that control, though running and maintaining it then falls on you. Read the self-hosting documentation to see what that involves.

You’ll also need to get used to Convex’s database model. Plan your indexes deliberately and keep transactions bounded, and write external calls assuming they can fail and need retries.

If you’re continuing with the app, a great next step is adding shared projects with viewer and editor roles. Create a membership table, protect every project query and mutation, and write your cross-user tests before building the invitation screen.

Want me to talk about your product? You can sponsor this site.

Related posts about database: