---
title: "Better Auth"
description: "Run Better Auth inside Convex with @convex-dev/better-auth, use it from Nuxt through @nuxtjs/better-auth, and render signed-in pages on the server."
canonical_url: "https://nuxt-convex.onmax.me/integrations/better-auth"
---
# Better Auth

> Run Better Auth inside Convex with @convex-dev/better-auth, use it from Nuxt through @nuxtjs/better-auth, and render signed-in pages on the server.

The recommended setup runs Better Auth inside your Convex deployment, as the `@convex-dev/better-auth` component. Users, sessions and accounts live in Convex. The Nuxt app runs `@nuxtjs/better-auth` in client-only mode, and `nuxt-convex` connects the two:

- it proxies `/api/auth/**` to your Convex site URL, so auth stays on your app's origin and its cookies are first-party
- on the server, it exchanges the session cookie for a Convex JWT, so SSR and [server routes](https://nuxt-convex.onmax.me/nuxt-module/server-routes) run as the user
- in the browser, it gives the realtime client the same token, and clears it on sign-out

## Before you begin

This integration is Nuxt-only. The supported baseline is the email/password flow exercised by the playground. GitHub auth and other social providers work through Better Auth's usual config, but they stay optional and secondary compared with the supported email/password path.

Treat this integration as dependency-constrained. The versions below are a tested set, not a promise that every nearby version combination works.

## Install the tested stack

```bash [Terminal]
pnpm add @nuxtjs/better-auth@0.3.12 \
  @convex-dev/better-auth@0.12.5 \
  better-auth@1.6.33
```

<warning>

`@convex-dev/better-auth@0.12.5` only works with `better-auth` 1.6: it imports `better-auth/plugins/oidc-provider`, which 1.7 removed, so `npx convex dev` fails to bundle with 1.7 ([get-convex/better-auth#444](https://github.com/get-convex/better-auth/pull/444)). `@nuxtjs/better-auth` declares `better-auth >=1.7`, but its `clientOnly` mode works with 1.6. Pin `better-auth@1.6.33` and silence the peer range:

```yaml [pnpm-workspace.yaml]
peerDependencyRules:
  allowedVersions:
    '@nuxtjs/better-auth>better-auth': 1.6.33
```

```json [package.json (npm)]
{
  "overrides": {
    "better-auth": "1.6.33"
  }
}
```

</warning>

## Set up Better Auth in Convex

Register the component:

```ts [convex/convex.config.ts]
import betterAuth from '@convex-dev/better-auth/convex.config'
import { defineApp } from 'convex/server'

const app = defineApp()
app.use(betterAuth)

export default app
```

Let Convex accept the JWTs Better Auth issues:

```ts [convex/auth.config.ts]
import type { AuthConfig } from 'convex/server'
import { getAuthConfigProvider } from '@convex-dev/better-auth/auth-config'

export default { providers: [getAuthConfigProvider()] } satisfies AuthConfig
```

Create the auth instance. `SITE_URL` is the public URL of the Nuxt app, because every auth request reaches Convex through its proxy:

```ts [convex/auth.ts]
import type { GenericCtx } from '@convex-dev/better-auth'
import type { DataModel } from './_generated/dataModel'
import { createClient } from '@convex-dev/better-auth'
import { convex } from '@convex-dev/better-auth/plugins'
import { betterAuth } from 'better-auth/minimal'
import { components } from './_generated/api'
import authConfig from './auth.config'

const siteUrl = process.env.SITE_URL!

export const authComponent = createClient<DataModel>(components.betterAuth)

export function createAuth(ctx: GenericCtx<DataModel>) {
  return betterAuth({
    baseURL: siteUrl,
    trustedOrigins: [siteUrl],
    database: authComponent.adapter(ctx),
    emailAndPassword: { enabled: true, requireEmailVerification: false },
    plugins: [convex({ authConfig })],
  })
}
```

Serve its routes from the deployment's HTTP actions:

```ts [convex/http.ts]
import { httpRouter } from 'convex/server'
import { authComponent, createAuth } from './auth'

const http = httpRouter()
authComponent.registerRoutes(http, createAuth)

export default http
```

Set the secret and the app URL on the deployment:

```bash [Terminal]
npx convex env set BETTER_AUTH_SECRET "$(openssl rand -base64 32)"
npx convex env set SITE_URL http://localhost:3000
```

Repeat with `--prod` and your production URL for the production deployment.

## Configure Nuxt

```ts [nuxt.config.ts]
export default defineNuxtConfig({
  modules: ['nuxt-convex', '@nuxtjs/better-auth'],
  auth: {
    // Better Auth runs in Convex; this app only runs its client
    clientOnly: true,
  },
})
```

With `@nuxtjs/better-auth` installed, `nuxt-convex` picks the `better-auth` provider and turns the `/api/auth/**` proxy on. Both are configurable through [`convex.auth`](https://nuxt-convex.onmax.me/api-reference/module-configuration#auth), for example to change `basePath`.

Point the Better Auth client at the proxy and add the Convex plugin:

```ts [app/auth.config.ts]
import { convexClient } from '@convex-dev/better-auth/client/plugins'
import { defineClientAuth } from '@nuxtjs/better-auth/config'

export default defineClientAuth(({ siteUrl }) => ({
  baseURL: new URL('/api/auth', import.meta.client ? window.location.origin : siteUrl).toString(),
  plugins: [convexClient()],
}))
```

`@nuxtjs/better-auth` also creates `server/auth.config.ts` when it's installed. Client-only mode doesn't use it; keep it, or the module recreates it.

The Nuxt app needs no Better Auth secret: it lives in Convex. `@nuxtjs/better-auth` still warns `Skipping auth secret prompt` on the first `nuxt prepare`; in client-only mode you can ignore it.

The app needs the Convex URL as usual. The Convex site URL comes from `CONVEX_SITE_URL` (which `npx convex dev` writes to `.env.local`) or is derived from the deployment URL. Set `NUXT_PUBLIC_SITE_URL` to the app's own public URL in the production runtime environment, next to `NUXT_PUBLIC_CONVEX_URL`; without it `@nuxtjs/better-auth` warns `set runtimeConfig.public.siteUrl` at build time. The `app/auth.config.ts` above uses the browser's origin on the client, so the warning is harmless in development.

## Use it

Sign up, sign in and sign out with `@nuxtjs/better-auth`'s composables, and read Convex data as the user. Better Auth requires a `name` on sign-up:

```vue [app/pages/signup.vue]
<script setup lang="ts">
const signUp = useSignUp('email')
const form = reactive({ name: '', email: '', password: '' })

async function submit() {
  await signUp.execute(form)
  if (signUp.status.value === 'success')
    await navigateTo('/dashboard')
}
</script>
```

```vue [app/pages/login.vue]
<script setup lang="ts">
const signIn = useSignIn('email')
const form = reactive({ email: '', password: '' })

async function submit() {
  await signIn.execute(form)
  if (signIn.status.value === 'success')
    await navigateTo('/dashboard')
}
</script>
```

```vue [app/components/SignOutButton.vue]
<script setup lang="ts">
const signOut = useSignOut()
</script>

<template>
  <button @click="signOut.execute()">
    Sign out
  </button>
</template>
```

```vue [app/pages/dashboard.vue]
<script setup lang="ts">
import { api } from '#convex/api'

// Rendered on the server as the signed-in user
const { data: tasks } = await useConvexQuery(api.tasks.list, {}, { auth: 'required' })
</script>
```

In Convex functions, `ctx.auth.getUserIdentity()` returns the user, with the Better Auth user id as `subject`.

Don't call `useConvexAuth({ fetchToken })` yourself: the module's client plugin does it, and signs the realtime client out when the Better Auth session ends.

## Verify the result

The integration is working when:

- email/password sign-up and sign-in succeed, and the session cookie is set on your app's domain
- `GET /api/auth/convex/token` returns `{ "token": "..." }` while signed in
- a page with an awaited query renders the user's data in its server HTML
- signing out clears the data without a reload

The playground's **Auth** page and the **Diagnostics** section of its **Settings** page are the validation reference for the supported flow.

## Rotating `BETTER_AUTH_SECRET`

Better Auth encrypts the private keys it signs JWTs with (its JWKS) using `BETTER_AUTH_SECRET`. After you change the secret, the stored keys can't be decrypted and token requests fail with `Failed to decrypt private key`. Delete the stored keys, and Better Auth creates new ones on the next request:

```bash [Terminal]
npx convex run --component betterAuth adapter:deleteMany '{"input":{"model":"jwks"},"paginationOpts":{"numItems":100,"cursor":null}}'
```

Add `--prod`, or run it with a production deploy key, for the production deployment. Sessions aren't affected: clients fetch a new token, signed with the new key, on their next request.

## Migrating from the `convex` database provider

Earlier releases offered `auth.database.provider: 'convex'`, which ran Better Auth in Nuxt and stored its tables in Convex through `createConvexHttpAdapter` from `nuxt-convex/better-auth`. Both were removed: they needed public, unauthenticated functions over the auth tables. Setting that provider now fails the build with a migration message.

To migrate, move Better Auth into Convex as shown above, set `auth.clientOnly: true`, and delete the old auth table functions from your `convex/` directory. The component stores its data in its own tables, not in the ones the old adapter wrote to, so plan a data migration for existing users.

## Next steps

- [Authenticated SSR](https://nuxt-convex.onmax.me/nuxt-module/authenticated-ssr) for the token flow and caching
- [Security](https://nuxt-convex.onmax.me/nuxt-module/security) for the proxy's header handling
- [R2](https://nuxt-convex.onmax.me/integrations/r2) if your app also needs bucket uploads


## Sitemap

See the full [sitemap](https://nuxt-convex.onmax.me/sitemap.md) for all pages.
