#Client side convex id validation
4 messages · Page 1 of 1 (latest)
Hi @limber grail. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
To validate Convex ID values on the client before running mutations or queries, it's important to understand that Convex IDs (e.g., Id<"tableName">) are just strings at runtime—TypeScript types are erased on the client, so you can't use TypeScript to enforce ID validity at runtime. This means you can't truly validate that a string is a valid Convex ID for a specific table on the client side, but you can do some basic checks:
1. Check that the value is a string
On the client, you can check that the ID is a string before sending it to Convex. For example:
if (typeof id !== "string") {
// Handle invalid ID
}
Validate Id<"tableName"> or Doc<"tableName"> on the client or server? (Discord)
2. (Optional) Check string length
Convex IDs are typically 32 characters long. You can add a length check as a pragmatic approach:
if (typeof id !== "string" || id.length !== 32) {
// Handle invalid ID
}
Validate Id<"tableName"> or Doc<"tableName"> on the client or server? (Discord)
3. Server-side validation is authoritative
The most robust validation happens server-side. If you want to handle "not found" errors gracefully, consider accepting the ID as a string in your Convex function, then use ctx.db.normalizeId and ctx.db.get to validate and fetch the document. This allows you to throw a custom error if the ID is invalid or not found, rather than letting the validator throw a generic error:
// In your Convex function
args: { id: v.string() },
handler: async (ctx, args) => {
const id = ctx.db.normalizeId("tableName", args.id);
if (!id) throw new ConvexError("Invalid ID");
const doc = await ctx.db.get(id);
if (!doc) throw new ConvexError("Not found");
// ...rest of your logic
}
Value does not match validator (Discord)
Summary
- On the client, check that the ID is a string (and optionally its length).
- For full validation, handle IDs as strings on the server and use
normalizeIdandgetto validate and fetch documents, allowing you to return custom errors instead of generic validator errors.