#normalizeId in action
3 messages · Page 1 of 1 (latest)
Hi @raw dock. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
You can use the normalizeId method inside a Convex action to validate and normalize a string ID (for example, one received from a URL or external source) to ensure it matches the expected table's ID format. This is useful when you want to accept a string, check if it's a valid ID for a specific table, and handle invalid IDs gracefully.
Usage Example in an Action:
export const myAction = action({
args: { id: v.string() }, // Accept as string
handler: async (ctx, args) => {
const normalizedId = ctx.db.normalizeId("myTable", args.id);
if (!normalizedId) {
throw new Error("Invalid ID for myTable");
}
const doc = await ctx.db.get(normalizedId);
// handle doc (could be null if not found)
},
});
normalizeIdreturns the normalized ID if the string is a valid ID for the given table, ornullif not.- This does not check if the document exists—just that the ID is valid for the table. You can then use
ctx.db.get(normalizedId)to fetch the document, which will returnnullif it doesn't exist.
This approach is recommended when you want to provide a custom error message for invalid IDs, rather than letting the default Convex argument validator error be thrown. It is especially useful when IDs come from untrusted sources, such as URL parameters or external systems, and you want to handle errors in a user-friendly way.
References: