---
title: "Hook into sign-in and sign-up"
description: "Decide who may sign in with canSignIn, run your own code when an account is created or deleted, and add Better Auth hooks of your own that compose with the package's."
canonical_url: "https://nuxt-backend.dev/docs/build/auth/sign-in/hooks"
---
# Hook into sign-in and sign-up

> Decide who may sign in with canSignIn, run your own code when an account is created or deleted, and add Better Auth hooks of your own that compose with the package's.

Version: nuxt-backend 0.6.x · Tab: Build · Kind: how-to · Status: stable

Every page: [llms.txt](https://nuxt-backend.dev/llms.txt) · Skill for coding agents: [nuxt-backend](https://nuxt-backend.dev/.well-known/skills/nuxt-backend/SKILL.md)

Commands use npm; use your project's package manager.

- [API reference](https://nuxt-backend.dev/docs/reference/api/auth)
- [Source](https://github.com/qruto/nuxt-backend/blob/main/src/convex/client/auth-types.ts)

`setupAuth` asks your code at three moments: before anyone signs in or signs up (`canSignIn`), once an account exists (`onUserCreated`), and once it is deleted (`onUserDeleted`). Each one gets the request's full Convex context, so it can read your tables, schedule work or start a workflow. Better Auth's own hooks are open too, and run beside the package's.

## Gate who signs in

`canSignIn(ctx, { email, isNewUser, purpose })` answers `true`, or `{ allowed: false, message? }` to refuse. It is asked at four points, named by `purpose`:

<table>
<thead>
  <tr>
    <th>
      <code>
        purpose
      </code>
    </th>
    
    <th>
      Asked
    </th>
    
    <th>
      <code>
        isNewUser
      </code>
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        sign-in
      </code>
    </td>
    
    <td>
      before a sign-in code is sent to <code>
        email
      </code>
    </td>
    
    <td>
      whether the address has no account yet
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        user-create
      </code>
    </td>
    
    <td>
      before any account is created, by any route
    </td>
    
    <td>
      always <code>
        true
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        session
      </code>
    </td>
    
    <td>
      before a session opens for an existing account, a passkey sign-in included
    </td>
    
    <td>
      always <code>
        false
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        email-change
      </code>
    </td>
    
    <td>
      before a code goes to a signed-in person's new address, and again before the account moves to it
    </td>
    
    <td>
      always <code>
        false
      </code>
    </td>
  </tr>
</tbody>
</table>

`email` is lower-cased, as Better Auth holds it. A closed beta for one domain refuses new accounts and new addresses elsewhere, and lets every existing account in:

```ts [backend/auth.ts]
export const { authComponent, createAuth, getAuthUser } = setupAuth(components, query, {
  email,
  rateLimiter,
  canSignIn: async (_ctx, { email, purpose }) => {
    if (purpose !== 'user-create' && purpose !== 'email-change') return true
    return email.endsWith('@acme.com')
      ? true
      : { allowed: false, message: 'Acme is open to acme.com addresses for now.' }
  },
})
```

A refusal is a `forbidden` error with reason `sign_in_refused`, and `useLoginFlow().error` shows your `message` as written. Without one, the person reads the `errors.forbidden_sign_in_refused` label ("Sign-in is by invitation right now." in English). To read an allow-list of your own, call it from the gate: `await ctx.runQuery(internal.beta.isAllowed, { email })`.

<warning>

**Refuse at user-create, not at sign-in.** A refusal at `sign-in` answers whoever typed the address, so a gate that refuses new addresses there tells anyone which addresses have an account. Refused at `user-create`, the code goes out either way, and only the person holding the mailbox reads the refusal. The cost is a code email to every address that asks.

At `email-change` the gate answers a signed-in person about an address they typed. With `rateLimiter` passed, each answer costs one of the account's `emailChange` requests (five an hour), so an account cannot probe it for free.

</warning>

A gate that refuses every new address also refuses the people your members invite to a workspace and the recipients of gifts, since both sign up as new accounts. [Launch phases](https://nuxt-backend.dev/docs/build/growth/launch) run waitlist and invite-only launches and admit those people themselves, and `canSignIn` stays your extra veto on top.

## Run code when an account is created

`onUserCreated(ctx, user)` runs in the request that created the account, after its welcome email went out. `user` holds `id`, `email` and `name`. The scaffold starts the onboarding sequence there:

```ts [backend/auth.ts]
setupAuth(components, query, {
  email,
  onUserCreated: async (ctx, user) => {
    await workflow.start(ctx, internal.workflows.onSignup, {
      userId: user.id,
      email: user.email,
      name: user.name,
    })
  },
})
```

Better Auth runs a failed after-hook a second time, so the hook can run twice for one account: key what it starts on `user.id`. A second failure fails the sign-up request, and the account stays created. [Email sequences](https://nuxt-backend.dev/docs/build/growth/engage/lifecycle-emails) has the onboarding sequence the scaffold ships.

## Run code when an account is deleted

`onUserDeleted(ctx, user)` runs once an account is deleted, after any `user.deleteUser.afterDelete` you pass in `authOptions`: tell a team channel, stop a workflow. Erasing your own tables does not belong here. A source of [`setupAccount`](https://nuxt-backend.dev/docs/build/auth/accounts/data#join-your-own-tables) runs for every deletion, server code's included, and is retried when it fails.

## Add Better Auth hooks of your own

`databaseHooks` you pass in `authOptions` compose with the package's: per model and operation, the package's hook runs first and yours second. A `before` hook receives the entity as the package left it (a new session already carries its active workspace), and a `false` from either side aborts the write.

To refuse with a message, throw `APIError`, re-exported from `nuxt-backend/auth` so there is no `better-auth` dependency to add. The client gets the status and the message:

```ts [backend/auth.ts]
import { APIError, setupAuth } from 'nuxt-backend/auth'

setupAuth(components, query, {
  email,
  authOptions: {
    databaseHooks: {
      user: {
        update: {
          before: async (user) => {
            if (typeof user.name === 'string' && user.name.trim().length > 60) {
              throw new APIError('BAD_REQUEST', { message: 'Keep your name to 60 characters.' })
            }
          },
        },
      },
    },
  },
})
```

Leave out plugins that add tables or fields: the `backend` component owns the auth schema ([Auth setup](https://nuxt-backend.dev/docs/build/auth/setup#change-the-auth-route)).

## Verify

1. With the closed-beta gate above, sign in with an address of another domain: the code arrives, and checking it shows your message.
2. Sign in with an existing account of another domain: it signs in.
3. Check the `convex dev` console after a sign-up: your `onUserCreated` ran once.

## Related

- [Launch in phases](https://nuxt-backend.dev/docs/build/growth/launch): the phases `canSignIn` sits on top of.
- [Hooks](https://nuxt-backend.dev/docs/reference/backend/hooks#setupauth-cansignin): when each hook runs, how often, and what a throw does.
- [Auth setup](https://nuxt-backend.dev/docs/build/auth/setup#cross-component-wiring): everything else `setupAuth` takes.
- [Errors](https://nuxt-backend.dev/docs/reference/backend/errors#forbidden): `forbidden` and its reasons.


## Sitemap

See the full [sitemap](https://nuxt-backend.dev/sitemap.md) for all pages.
