Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 60 additions & 17 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,27 +1,70 @@
<p align="center">
<img src="https://raw.githubusercontent.com/onmax/nuxt-better-auth/main/.github/og.png" alt="Nuxt Better Auth" width="100%">
<br>
<sub>Designed by <a href="https://github.com/HugoRCD">HugoRCD</a></sub>
</p>
# `@onmax/nuxt-better-auth`

<h1 align="center">@onmax/nuxt-better-auth</h1>
Nuxt module for [Better Auth](https://better-auth.com) with Nuxt-native route protection, SSR-safe session access, auto-imported helpers, and optional NuxtHub-backed schema generation.

<p align="center">Nuxt module for <a href="https://better-auth.com">Better Auth</a></p>
> [!WARNING]
> This package is still in alpha. Expect API and behavior changes before a stable release.

<p align="center">
<a href="https://npmjs.com/package/@onmax/nuxt-better-auth"><img src="https://img.shields.io/npm/v/@onmax/nuxt-better-auth/latest.svg?style=flat&colorA=020420&colorB=00DC82" alt="npm version"></a>
<a href="https://npm.chart.dev/@onmax/nuxt-better-auth"><img src="https://img.shields.io/npm/dm/@onmax/nuxt-better-auth.svg?style=flat&colorA=020420&colorB=00DC82" alt="npm downloads"></a>
<a href="https://npmjs.com/package/@onmax/nuxt-better-auth"><img src="https://img.shields.io/npm/l/@onmax/nuxt-better-auth.svg?style=flat&colorA=020420&colorB=00DC82" alt="License"></a>
<a href="https://nuxt.com"><img src="https://img.shields.io/badge/Nuxt-020420?logo=nuxt.js" alt="Nuxt"></a>
</p>
## Who this is for

> [!WARNING]
> This library is a work in progress and not ready for production use.
Use this module if you want Better Auth in a Nuxt 4 app and you want the Nuxt-specific pieces handled for you:

- `useUserSession()` for reactive auth state
- `requireUserSession(event)` and related server helpers
- route protection through `routeRules` and `definePageMeta({ auth })`
- generated `server/auth.config.ts` and `app/auth.config.ts`
- optional NuxtHub database integration and schema generation

## Install the module

For the fastest path in a Nuxt 4 app:

```bash
npx nuxi module add @onmax/nuxt-better-auth@alpha
```

Then create or confirm these files:

- `server/auth.config.ts`
- `app/auth.config.ts`
- `.env` with `NUXT_BETTER_AUTH_SECRET`

For the full setup flow, follow the [installation guide](https://better-auth.nuxt.dev/getting-started/installation).

## Choose your setup path

- Use [NuxtHub integration](https://better-auth.nuxt.dev/integrations/nuxthub) if you want the shortest path to database-backed auth.
- Use [custom database setup](https://better-auth.nuxt.dev/guides/custom-database) if you already have your own database stack.
- Use [external auth backend](https://better-auth.nuxt.dev/guides/external-auth-backend) if Better Auth runs in a separate service.
- Use [database-less mode](https://better-auth.nuxt.dev/guides/database-less-mode) for stateless or OAuth-first setups with clear tradeoffs.

## Documentation

**[better-auth.nuxt.dev](https://better-auth.nuxt.dev/)**
The documentation site is at [better-auth.nuxt.dev](https://better-auth.nuxt.dev).

Recommended reading order:

1. [Quickstart](https://better-auth.nuxt.dev/getting-started)
2. [Installation](https://better-auth.nuxt.dev/getting-started/installation)
3. [Configuration](https://better-auth.nuxt.dev/getting-started/configuration)
4. [Client setup](https://better-auth.nuxt.dev/getting-started/client-setup)
5. [Route protection](https://better-auth.nuxt.dev/core-concepts/route-protection)

## Development

```bash
pnpm install
pnpm dev:docs
```

Useful commands:

- `pnpm dev` to run the playground
- `pnpm dev:docs` to run the docs site
- `pnpm lint` to lint the repo
- `pnpm test` to run the test suite
- `pnpm build:docs` to build the docs site

## License

MIT
[MIT](https://github.com/nuxt-modules/better-auth/blob/main/LICENSE)
111 changes: 46 additions & 65 deletions docs/content/1.getting-started/0.index.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,112 +4,93 @@ description: Nuxt Better Auth integrates Better Auth with Nuxt for route protect
navigation.icon: i-lucide-sparkles
---

Nuxt Better Auth integrates **Nuxt** and **Better Auth**, the TypeScript-first authentication library. You get route protection, session management, and schema generation with minimal setup. The plugin ecosystem adds features like 2FA, organizations, and passkeys.
Use this page when you want the fastest path to a working Nuxt 4 setup.

::card{to="https://demo-nuxt-better-auth.onmax.me" target="_blank" icon="i-lucide-external-link"}
**Live Demo** – Try the authentication flow in action.
::
This quickstart assumes:

## Features
- you want the default full-mode setup
- you are using `pnpm`
- you want a local login flow working before you customize providers or plugins

This module brings Nuxt-specific enhancements on top of Better Auth:
If you already know you need a different architecture, jump to [NuxtHub](/integrations/nuxthub), [custom database](/guides/custom-database), or [external auth backend](/guides/external-auth-backend).

::docs-features
---
features:
- title: Auto Configuration
description: Auto-wires API routes, middleware, and schema with sensible defaults
- title: Route Protection
description: Declarative page and API route guards
- title: Schema Generation
description: Auto-generate Drizzle schemas
- title: Reactive Sessions
description: "`useUserSession()` with SSR support"
- title: Database Flexibility
description: Works standalone or with NuxtHub
- title: Type Safety
description: Full TypeScript inference
- title: Auto Imports
description: Composables and utils ready to use
- title: Server Utilities
description: Auth helpers for your API routes
- title: Powered by Better Auth
description: 2FA, OAuth, SSO, organizations, and more
href: https://www.better-auth.com
---
::
## What you will end up with

## Why Nuxt Better Auth?
After this guide you should have:

Building authentication from scratch is hard. Wiring up Better Auth with Nuxt manually involves:
- Setting up API handlers
- Syncing client/server state
- Handling redirects
- Managing database schemas (if using a database)
- `server/auth.config.ts` and `app/auth.config.ts`
- Better Auth handlers mounted at `/api/auth/*`
- a valid `NUXT_BETTER_AUTH_SECRET`
- a reactive `useUserSession()` composable in your app

This module does all of that for you. Just configure your auth providers and the module handles the rest.
## Before you begin

## Quick Start
- Nuxt `4.x`
- a local `.env` file
- a development server you can start with `pnpm dev`

Get a working login in 5 minutes with NuxtHub (SQLite).
## Quickstart

::steps

### Install
### Install the module

```bash
npx nuxi module add @onmax/nuxt-better-auth@alpha @nuxthub/core
npx nuxi module add @onmax/nuxt-better-auth@alpha
```

### Configure
### Add your secret

```ts [nuxt.config.ts]
export default defineNuxtConfig({
hub: { db: 'sqlite' },
})
```
Create or update `.env`:

```ini [.env]
NUXT_BETTER_AUTH_SECRET="generate-a-32-char-secret"
NUXT_BETTER_AUTH_SECRET="replace-with-a-random-32-character-secret"
```

### Create Config Files
Use a high-entropy value. The module also accepts `BETTER_AUTH_SECRET` as a fallback, but `NUXT_BETTER_AUTH_SECRET` is the recommended variable.

### Create the server config

```ts [server/auth.config.ts]
import { defineServerAuth } from '@onmax/nuxt-better-auth/config'

export default defineServerAuth({
emailAndPassword: { enabled: true },
emailAndPassword: {
enabled: true,
},
})
```

### Create the client config

```ts [app/auth.config.ts]
import { defineClientAuth } from '@onmax/nuxt-better-auth/config'

export default defineClientAuth({})
```

### Run
### Start Nuxt

::code-group{sync="pm"}
```bash [pnpm]
```bash
pnpm dev
```
```bash [npm]
npm run dev
```
::

::

You now have API routes at `/api/auth/*`, a reactive `useUserSession()` composable, and route protection via `definePageMeta`.
## Verify the result

Check these success signals:

- your app starts without auth-related module errors
- `/api/auth/*` routes are registered
- `useUserSession()` is available in a page or component
- the generated config files match your project structure

## Recommended Path for Beginners
If you use a custom `srcDir`, the client config lives there instead of `app/`.

If this is your first setup, follow this order:
## Next steps

1. [Installation](/getting-started/installation)
2. [Configuration](/getting-started/configuration)
3. [Client Setup](/getting-started/client-setup)
4. [Route Protection](/core-concepts/route-protection)
5. [API Reference](/api/composables)
1. Follow [installation](/getting-started/installation) for the complete setup checklist.
2. Read [configuration](/getting-started/configuration) before adding providers or plugins.
3. Set up [client usage](/getting-started/client-setup) in your pages and forms.
4. Add [route protection](/core-concepts/route-protection) once the login flow works.
26 changes: 21 additions & 5 deletions docs/content/1.getting-started/1.installation.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,17 @@ Install @onmax/nuxt-better-auth in my Nuxt 4 app.
- Create `server/auth.config.ts` using `defineServerAuth` from `@onmax/nuxt-better-auth/config`
- Create `app/auth.config.ts` using `defineClientAuth` from `@onmax/nuxt-better-auth/config`
- The module auto-injects `secret` and `baseURL` — do not configure them manually

Read more: https://better-auth.nuxt.dev/raw/getting-started/installation.md
Source: https://github.com/nuxt-modules/better-auth
```

::

Use this page when you want the full install checklist rather than the shorter quickstart.

## Prerequisites

- Nuxt v4.0+
- a package manager configured for your app
- a local `.env` file or deployment environment variable system

## Add to project

Expand All @@ -36,7 +37,7 @@ Source: https://github.com/nuxt-modules/better-auth
npx nuxi module add @onmax/nuxt-better-auth@alpha
```

### Set Environment Variables
### Set environment variables

::tip{icon="i-lucide-sparkles"}
When you install the module with `nuxi module add`, it prompts you to generate `NUXT_BETTER_AUTH_SECRET` and can append it to your `.env`. `BETTER_AUTH_SECRET` still works as a compatibility fallback. In CI/test environments it auto-generates the secret.
Expand Down Expand Up @@ -73,7 +74,7 @@ The module auto-detects the URL on Vercel, Cloudflare Pages, and Netlify. Set ma
NUXT_PUBLIC_SITE_URL=https://your-domain.com
```

### Create Configuration Files
### Create configuration files

::tip{icon="i-lucide-sparkles"}
During module install, `server/auth.config.ts` and `<srcDir>/auth.config.ts` are scaffolded if missing. The client config is placed in your `srcDir` (e.g., `app/` or project root).
Expand Down Expand Up @@ -102,6 +103,21 @@ export default defineClientAuth({})

::

## Verify the installation

Confirm all of the following:

- Nuxt starts without missing-config errors
- `server/auth.config.ts` exists
- `app/auth.config.ts` or your `srcDir` equivalent exists
- `NUXT_BETTER_AUTH_SECRET` is available at runtime

## Next steps

- Continue with [configuration](/getting-started/configuration) to set module options and route protection.
- Continue with [client setup](/getting-started/client-setup) to wire sign-in and sign-out flows.
- If you need durable persistence, pick either [NuxtHub integration](/integrations/nuxthub) or [custom database](/guides/custom-database).

::callout{icon="i-lucide-database" to="/integrations/nuxthub"}
**Need database persistence?** See [NuxtHub Integration](/integrations/nuxthub) for auto-generated schemas and full database support.
::
Expand Down
20 changes: 17 additions & 3 deletions docs/content/1.getting-started/2.configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,12 @@ Configure @onmax/nuxt-better-auth module options and server auth.
- The module auto-injects `secret` and `baseURL` — do not set them in defineServerAuth
- Base URL priority: runtimeConfig > request URL > platform env vars > localhost
- Set `NUXT_PUBLIC_SITE_URL` for custom domains or deterministic OAuth callbacks

Read more: https://better-auth.nuxt.dev/raw/getting-started/configuration.md
Source: https://github.com/nuxt-modules/better-auth
```

::

Use this page when the module is installed and you want to control runtime behavior in `nuxt.config.ts`, `server/auth.config.ts`, and `app/auth.config.ts`.

## Module Configuration

```ts [nuxt.config.ts]
Expand Down Expand Up @@ -266,6 +265,21 @@ Use `NUXT_BETTER_AUTH_SECRET` as the primary secret variable. `BETTER_AUTH_SECRE

## For Module Authors

## Recommended order

1. Configure the module in `nuxt.config.ts`.
2. Configure Better Auth behavior in `server/auth.config.ts`.
3. Configure client plugins in `app/auth.config.ts`.
4. Add route protection with `routeRules` or `definePageMeta({ auth })`.

## Verify the result

After configuration changes:

- restart the Nuxt dev server if you changed schema- or plugin-related settings
- confirm your app boots without missing-config errors
- confirm route protection works on at least one protected page and one protected API route

Other Nuxt modules can extend the authentication configuration:

```ts
Expand Down
33 changes: 30 additions & 3 deletions docs/content/1.getting-started/3.client-setup.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,12 @@ Set up the client auth config for @onmax/nuxt-better-auth.
- Add client plugin equivalents for every server plugin (e.g. `adminClient()` from `better-auth/client/plugins`)
- The module calls the factory with the correct `baseURL` at runtime
- `useUserSession()` is auto-imported and provides `user`, `session`, `loggedIn`, `ready`, `signIn`, `signUp`, `signOut`

Read more: https://better-auth.nuxt.dev/raw/getting-started/client-setup.md
Source: https://github.com/nuxt-modules/better-auth
```

::

Use this page when the server config exists and you want to wire the Better Auth client into your Nuxt app.

## Create the Client Config

Create `app/auth.config.ts` with a default export using `defineClientAuth`.
Expand Down Expand Up @@ -72,3 +71,31 @@ export default defineClientAuth({
```

:read-more{to="https://www.better-auth.com/docs/plugins" title="All Better Auth plugins"}

## Use the client in your app

`useUserSession()` is auto-imported in pages and components.

```vue [pages/login.vue]
<script setup lang="ts">
definePageMeta({ auth: 'guest' })

const { signIn } = useUserSession()

async function login(email: string, password: string) {
await signIn.email(
{ email, password },
{ onSuccess: () => navigateTo('/app') },
)
}
</script>
```

## Verify the result

Confirm all of the following:

- `useUserSession()` is available without a manual import
- `client` is available on the browser after hydration
- client plugins are registered on both server and client when required by Better Auth
- sign-in and sign-out update `user`, `session`, and `loggedIn`
Loading
Loading