RadiantFrogR
Convex Communityโ€ข10mo agoโ€ข
4 replies
RadiantFrog

Tanstack: How to call a Convex mutation from createServerFn?

I'm lost on how I can use Convex from the serverFn in Tanstack. Here is my attempt
const convex = new ConvexHttpClient(import.meta.env.VITE_CONVEX_URL);

// Define the input schema using Zod
const suggestMilestonesInputSchema = z.object({
  userId: z.string(),
  goal: z.any(), // Allow any type for goal for now
  language: z.string(),
});

export const suggestMilestones = createServerFn({
  method: "POST",
})
  .validator((person: unknown) => {
    return suggestMilestonesInputSchema.parse(person);
  })
  .handler(async (ctx) => {
    // Call mutation inside the handler
    await convex.mutation(api.user.increaseAISuggestions, { userId: userId as Id<"user"> });

  });


Here is my mutation
// Update user email
export const updateUserEmail = mutation({
  args: {
    userId: v.id("user"),
    email: v.string(),
  },
  handler: async (ctx, { userId, email }) => {
    await ctx.db.patch(userId, {
      email,
      updatedAt: new Date().toISOString(),
    });

    return { success: true };
  },
});


if there is any example boilerplate on how to call convex from the createServerFn handler that would be amazing. So I basically want to have some validations on the server side (does the user have enough credits)

I can see there is:
import { fetchMutation, fetchQuery } from "convex/nextjs";


but that requires met to set which I cannot do in a Vite project.
Error: Environment variable NEXT_PUBLIC_CONVEX_URL is not set.
Was this page helpful?