Skip to main content

Guest users

Give visitors a Better Auth identity and preserve guest profile data when they sign in.

Experimental. Semantic versioning does not cover this option.

Use Better Auth's anonymous plugin to give a visitor a real user and session. auth.requireUser(ctx) accepts that session. Check user.isAnonymous === true in Convex functions when guests must have less access. Guests have no verified email.

Enable the plugin

Do not enable twoFactor together with experimental.anonymous. The factory rejects this combination. Better Auth's anonymous linking hook does not wait for two-factor verification.

Create a local auth component with pnpm exec better-convex-nuxt auth init. Add anonymous() to convex/betterAuth/schemaPlugins.ts. Keep its generated jwt() entry. Regenerate the local schema:

bash
pnpm exec better-convex-nuxt auth schema \
  --config convex/betterAuth/schemaOptions.ts \
  --output convex/betterAuth

The plugin adds user.isAnonymous. The packaged component does not have this field. Commit the generated schema.ts and schemaMetadata.ts files. See Better Auth plugins for the local component setup.

convex/auth.ts
import { createBetterConvexAuth } from '@lupinum/better-convex-nuxt/better-auth/server'

import { components } from './_generated/api'
import type { DataModel } from './_generated/dataModel'

export const auth = createBetterConvexAuth<DataModel>(components.betterAuth, {
  experimental: { anonymous: true },
})

You can replace true with Better Auth's options: onLinkAccount, emailDomainName, generateName, generateRandomEmail, and disableDeleteAnonymousUser. Schema overrides are not supported. Custom email generators must return unique, valid email addresses.

app/convex-auth.ts
import { defineConvexAuthClient } from '@lupinum/better-convex-nuxt/better-auth/client'
import { anonymousClient } from 'better-auth/client/plugins'

export default defineConvexAuthClient({ plugins: [anonymousClient()] })

Call sign-in from an event handler. Do not call it on every page load:

ts
const { client } = useConvexAuth()
const result = await client.signIn.anonymous()
if (result.error) throw new Error(result.error.message)

Better Auth rejects another anonymous sign-in while the visitor has a guest session. Better Convex exchanges that session for a Convex session token. No separate guest session store is needed.

Allow guests in an invite-only app

beforeUserCreate also runs for each new guest. A guest has a generated address that nobody proved, so a check of emailVerified refuses every guest. Read user.isAnonymous to let guests through and check everyone else:

convex/auth.ts
export const auth = createBetterConvexAuth<DataModel>(components.betterAuth, {
  experimental: { anonymous: true },
  beforeUserCreate: async ({ ctx, user }) => {
    if (user.isAnonymous) return { allowed: true }
    if (!user.emailVerified) return { allowed: false }
    const invite = await ctx.runQuery(internal.members.findInvite, { email: user.email })
    return invite ? { allowed: true } : { allowed: false }
  },
})

Never give a guest access because of its address. Give it access in your Convex functions only after user.isAnonymous === true is checked.

Limit new guests per address

Each guest sign-in creates a user and a session. Better Convex gives each client address a bucket of 10 new guests that refills one every 6 minutes (10 per hour over time). Better Auth's own limit of 3 sign-ins per 10 seconds per address still applies, so even a full bucket lets guests in at that pace. The address is the verified client address that the auth proxy signs. A visitor over the limit gets 429. Change the limit with rateLimit:

convex/auth.ts
export const auth = createBetterConvexAuth<DataModel>(components.betterAuth, {
  experimental: { anonymous: { rateLimit: { window: 60 * 60, max: 30 } } },
})

window is in seconds, from 60 to 86,400. max is from 1 to 1,000. The bucket holds max sign-ins and refills one every window / max seconds, so it is not a fixed window: with the example, the bucket holds 30 guests and refills one every 2 minutes. Better Auth's limit of 3 sign-ins per 10 seconds still applies on top. Each guest sign-in writes the counter of its address in the component's rateLimit table. An IPv6 address counts by its /64 network, as in Better Auth's own limits, because one connection usually owns a whole /64. Many visitors behind one network address, for example at a school or an office, share one budget. The limit covers sign-in requests through /api/auth, not auth.api calls from your own Convex code.

Preserve profile data when the guest signs in

Better Auth calls onLinkAccount with the authenticated guest and the new user. This example preserves the guest's saved display name in the new profile:

convex/auth.ts
import { createBetterConvexAuth } from '@lupinum/better-convex-nuxt/better-auth/server'

import { components } from './_generated/api'
import type { DataModel } from './_generated/dataModel'

export const auth = createBetterConvexAuth<DataModel>(components.betterAuth, {
  experimental: {
    anonymous: {
      onLinkAccount: async ({ anonymousUser, newUser, ctx }) => {
        await ctx.context.adapter.update({
          model: 'user',
          where: [{ field: 'id', value: newUser.user.id }],
          update: { name: anonymousUser.user.name },
        })
      },
    },
  },
})

Use the IDs from the callback. Do not accept source or destination user IDs from the browser. The callback's ctx is a Better Auth endpoint context, not a Convex context. Its adapter accesses only the auth component.

To let a guest upgrade with a password, turn on password sign-in and add the email hook. Password sign-in is off until you pass emailAndPassword, and emailAndPassword: {} requires a verified address before the first sign-in. See Transactional auth email.

convex/auth.ts
// `sendAuthEmail` is your `email` hook, as in Transactional auth email.
export const auth = createBetterConvexAuth<DataModel>(components.betterAuth, {
  emailAndPassword: {},
  email: sendAuthEmail,
  experimental: { anonymous: true },
})

Email sign-up does not sign the user in: Better Convex keeps autoSignIn set to false. Keep the guest cookie. Sign up, ask the person to open the verification mail in the same browser, and call email sign-in after that:

ts
const { client } = useConvexAuth()
const credentials = {
  email: email.value,
  password: password.value,
}

async function upgrade() {
  const signup = await client.signUp.email({ ...credentials, name: name.value })
  if (signup.error) throw new Error(signup.error.message)
  // Show "Check your email to verify the address", then enable the sign-in button.
}

async function finishUpgrade() {
  const signin = await client.signIn.email(credentials)
  if (signin.error) throw new Error(signin.error.message)
}

The sign-in calls onLinkAccount. Better Auth then deletes the old guest and its auth records. Set disableDeleteAnonymousUser: true only when you need to retain that identity. That option does not expire old guests.

Remove old guests

Choose a retention period before enabling cleanup. This example deletes guests created more than 30 days ago, including guests with active sessions. It deletes each one with auth.deleteUser, the same way as deleting another user. Your onDelete triggers run, so a user projection deletes the guest's app user row and runs its erase hook.

All of this happens in one mutation per page, so the page is small: 25 guests. A larger page can exceed Convex's transaction limits, and then the whole page fails. Use fewer guests per page when your erase hook deletes many rows.

convex/guests.ts
import { v } from 'convex/values'

import { components, internal } from './_generated/api'
import { internalMutation } from './_generated/server'
import { auth } from './auth'

export const pruneGuests = internalMutation({
  args: {
    cutoff: v.optional(v.number()),
    cursor: v.optional(v.union(v.string(), v.null())),
  },
  handler: async (ctx, args): Promise<null> => {
    const cutoff = args.cutoff ?? Date.now() - 30 * 24 * 60 * 60 * 1000
    const users = await ctx.runQuery(components.betterAuth.adapter.findMany, {
      model: 'user',
      where: [
        { field: 'isAnonymous', value: true },
        { field: 'createdAt', operator: 'lt', value: cutoff },
      ],
      paginationOpts: { cursor: args.cursor ?? null, numItems: 25 },
    })
    for (const user of users.page) {
      if (typeof user.id !== 'string') throw new Error('Invalid auth user ID')
      await auth.deleteUser(ctx, user.id)
    }
    if (!users.isDone) {
      await ctx.scheduler.runAfter(0, internal.guests.pruneGuests, {
        cutoff,
        cursor: users.continueCursor,
      })
    }
    return null
  },
})
convex/crons.ts
import { cronJobs } from 'convex/server'

import { internal } from './_generated/api'

const crons = cronJobs()
crons.daily('Remove old guests', { hourUTC: 3, minuteUTC: 0 }, internal.guests.pruneGuests)
export default crons

Deletion removes the user's sessions and related auth records. Queries that read those component records become current. Without a user projection, add cleanup for application data in the same internal Convex mutation if your application stores guest documents.