#how do i define a schema that links to a better auth component table user, email field ?

3 messages · Page 1 of 1 (latest)

crystal lotusBOT
#

Hi @earnest owl. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

To define a schema in your Convex app that links to a Better Auth component table's user (specifically, the email field), you should:

  1. Add a reference field in your app's users table that stores the Better Auth user ID (commonly called authId).
  2. Index this field for efficient lookups.
  3. 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 authId reference.

Example: Accessing the Email

To access the email for a user, you can:

  • Query your app's users table by authId to get the user.
  • Use the authId to fetch the corresponding user from the Better Auth component table if you need the latest email.
#

Summary

  • Add an authId field 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.

For more details and migration steps, see the Better Auth migration guide and example schema.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: