Using Convex with Bolt.new

Important Note: When working with Convex in Bolt.new, you may notice that Claude (the AI assistant) sometimes has difficulty with the initial setup process since Convex integration is relatively new. For the smoothest experience, we recommend:

  1. Planning your Convex integration structure first
  2. Setting up the basic Convex configuration yourself
  3. Then using Claude for specific features and optimizations

For detailed setup instructions, refer to:

Convex is a powerful backend platform that works great with Bolt.new projects. Let’s walk through how to add it to your application.

What is Convex?

Convex combines several important backend features into one package:

  • Real-time Updates: Your app automatically updates when data changes, without writing extra code
  • TypeScript Support: Get autocomplete and catch errors before they happen
  • Built-in Authentication: Easily add user accounts and protect your data
  • Automatic Scaling: Your database grows with your app without configuration

Getting Started

1. Create a Convex Project

First, you’ll need to create a Convex project. Visit dashboard.convex.dev and:

  • Sign up for a free account
  • Click “New Project”
  • Give your project a name
  • Save your deployment URL (you’ll need this later)

2. Add Convex to Your Bolt.new Project

In your Bolt.new project, install the required packages:

npm install convex @convex/react

3. Set Up Your Environment

Create a .env file with your Convex URL:

NEXT_PUBLIC_CONVEX_URL=your_deployment_url_here

4. Initialize Convex

Create a new file convex/config.js:

export default {
  provider: process.env.NEXT_PUBLIC_CONVEX_URL
};

Creating Your First Database Table

1. Define Your Schema

Create convex/schema.ts:

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

export default defineSchema({
  // A simple tasks table
  tasks: defineTable({
    text: v.string(),
    completed: v.boolean(),
    createdAt: v.number()
  })
});

2. Add Some Basic Operations

Create convex/tasks.ts:

import { mutation, query } from "./_generated/server";

// Get all tasks
export const getTasks = query({
  handler: async (ctx) => {
    return await ctx.db.query("tasks").collect();
  }
});

// Add a new task
export const addTask = mutation({
  args: { text: v.string() },
  handler: async (ctx, args) => {
    await ctx.db.insert("tasks", {
      text: args.text,
      completed: false,
      createdAt: Date.now()
    });
  }
});

Using Convex in Your React Components

Here’s a simple example of how to use Convex in your app:

import { useQuery, useMutation } from "convex/react";

function TaskList() {
  // Get all tasks
  const tasks = useQuery("tasks/getTasks");
  // Get the function to add tasks
  const addTask = useMutation("tasks/addTask");

  if (!tasks) return <div>Loading...</div>;

  return (
    <div>
      <button onClick={() => addTask({ text: "New Task" })}>
        Add Task
      </button>
      
      <ul>
        {tasks.map(task => (
          <li key={task._id}>{task.text}</li>
        ))}
      </ul>
    </div>
  );
}

Real-time Updates Just Work

One of the best things about Convex is that real-time updates are automatic. When you:

  • Add a new task
  • Update a task
  • Delete a task

All connected clients will see the changes immediately, without writing any extra code!

Common Tasks

Adding New Data

const addItem = useMutation("items/add");

// In your component:
await addItem({
  name: "New Item",
  price: 9.99
});

Fetching Data

const items = useQuery("items/get");

// In your component:
if (!items) return <div>Loading...</div>;
return <div>{items.map(item => item.name)}</div>;

Updating Data

const updateItem = useMutation("items/update");

// In your component:
await updateItem({
  id: itemId,
  price: 19.99
});

Error Handling

Always wrap your Convex operations in try/catch blocks:

try {
  await addItem({ name: "New Item" });
} catch (error) {
  console.error("Failed to add item:", error);
  // Show error to user
}

Best Practices

  1. Keep It Simple

    • Start with basic CRUD operations
    • Add complexity only when needed
    • Use TypeScript for better code safety
  2. Data Organization

    • Create clear table names
    • Use consistent field names
    • Add indexes for frequently accessed fields
  3. Security

    • Always validate user input
    • Use authentication when needed
    • Test your security rules

Need Help?

Remember: Convex is designed to be developer-friendly. Start simple and add features as you need them!