#how do i define a schema that links to a better auth component table user, email field ?
3 messages · Page 1 of 1 (latest)
To define a schema in your Convex app that links to a Better Auth component table's user (specifically, the email field), you should:
- Add a reference field in your app's users table that stores the Better Auth user ID (commonly called
authId). - Index this field for efficient lookups.
- Sync the email field as needed, either by duplicating it in your app's table or by querying the Better Auth component table when needed.
Example: Linking App User to Better Auth User by authId
First, add an authId field to your app's users table. This field will store the ID of the corresponding user in the Better Auth component table:
import { defineSchema, defineTable } from "convex/server";
import { v } from "convex/values";
export default defineSchema({
users: defineTable({
email: v.string(),
authId: v.optional(v.string()), // Link to Better Auth user
})
.index("email", ["email"])
.index("authId", ["authId"]),
// ...other tables
});
Initially, keep authId optional for migration, then make it required once all users are linked. See migration guide for details.
Keeping Email in Sync
- You can duplicate the email field in your app's table and keep it in sync using triggers (see update user triggers).
- Alternatively, you can always query the Better Auth component table for the email using the
authIdreference.
Example: Accessing the Email
To access the email for a user, you can:
- Query your app's
userstable byauthIdto get the user. - Use the
authIdto fetch the corresponding user from the Better Auth component table if you need the latest email.
Summary
- Add an
authIdfield to your app's user table. - Index it for efficient lookups.
- Optionally, duplicate and sync the email field, or always fetch it from the Better Auth component table.