Hi folks!
As an engineer, I don’t trust things sent from the client-side; they must be validated and sanitized thoroughly. In this case, I’m referring to the user message ID.
Problem
From the info that I gathered so far, it seems in AI SDK 6, it is recommended (or implied) to trust the frontend generated ID for user messages. I know in the documentation for AI SDK UI: Chatbot Message Persistence, it says if you want to persist chat messages you should generate IDs on the server-side, but the example is only for assistant messages. We are still trusting the frontend generated IDs for user messages.
Potential Risks
This could result in three scenarios:
- Invalid IDs: User message has a weird ID like
a,abc, or a very large one. This can be prevented by adding validation. - ID Collisions: Multiple user messages share the same ID. In the UI, the latest message that shares the same ID will replace the older ones. On the backend, if messages are persisted using their IDs, this could overwrite the old messages depending on the implementation.
- ID Hijacking: User message reuses the ID of an assistant message. This could make the assistant message disappear.
Actually, since AI SDK doesn’t provide a persistence solution, I tested it with Mastra. For scenarios 2 and 3, they did overwrite the old messages in the database. I didn’t dig deeper, but I believe Mastra’s data is scoped using Resource ID, maybe even Thread ID. However, if developers roll their own solution, this could be a risk because one user could overwrite another user’s messages if message IDs are leaked, or perform attacks like deliberately generating IDs to overload one shard of the database.
Current Workaround
Currently, I overwrite the ID of the user message sent to the server. It feels really hacky, like an anti-pattern, and creates inconsistency if the client-side doesn’t reload; the ID in the UIMessage will still be the one generated by the frontend.
I’m out of options, so I’d like to discuss with anyone who’s interested in this topic. Maybe you have better solutions. Thanks!