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
2 changes: 2 additions & 0 deletions examples/nuxt-d1-cloudflare/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
BETTER_AUTH_SECRET=your-secret-key-at-least-32-characters
BETTER_AUTH_URL=http://localhost:3000
17 changes: 17 additions & 0 deletions examples/nuxt-d1-cloudflare/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Nuxt
.nuxt
.output
.data
.nitro
.cache

# Node
node_modules

# Cloudflare
.wrangler
.dev.vars

# Misc
.DS_Store
*.log
133 changes: 133 additions & 0 deletions examples/nuxt-d1-cloudflare/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
# Nuxt + Cloudflare Pages + D1 Example

A minimal example of using [Better Auth](https://better-auth.com) with **Nuxt**, **Cloudflare Pages**, and **Cloudflare D1** (SQLite).

## Features

- Email & password authentication
- Session management with SSR support
- Cloudflare D1 as the database (better-auth auto-detects D1 bindings)
- Auth middleware for protected routes
- Server-side session access via `auth.api.getSession()`

## Setup

### 1. Install dependencies

```bash
npm install
```

### 2. Create a D1 database

```bash
wrangler d1 create better-auth-db
```

Copy the `database_id` from the output and update `wrangler.toml`.

### 3. Generate & apply schema

Better Auth CLI auto-generates the SQL schema from your auth config:

```bash
# Generate schema SQL from your auth config
npm run db:generate

# Apply to local D1
npm run db:migrate

# Apply to remote D1 (production)
npm run db:migrate:remote
```

The `db:generate` script runs `npx auth generate --output ./migrations/schema.sql`, which reads your `server/lib/auth.ts` config and outputs the required tables (user, session, account, verification) as SQL.

### 4. Configure environment

Copy `.env.example` to `.env` and set your values:

```bash
cp .env.example .env
```

For production, set secrets via Cloudflare dashboard or:

```bash
wrangler pages secret put BETTER_AUTH_SECRET
wrangler pages secret put BETTER_AUTH_URL
```

### 5. Development

```bash
npm run dev
```

### 6. Deploy

```bash
npm run build
npm run deploy
```

## How it works

### D1 Integration

Better Auth auto-detects D1 bindings — just pass `env.DB` directly to the `database` option:

```ts
// server/lib/auth.ts
export function getAuth(event: H3Event) {
const { cloudflare } = event.context
const config = useRuntimeConfig(event)

return betterAuth({
database: cloudflare.env.DB, // auto-detected as D1
secret: config.betterAuthSecret,
baseURL: config.betterAuthUrl,
})
}
```

Because Cloudflare Pages exposes the D1 binding only on the incoming request context, `betterAuth` is instantiated per request inside `getAuth(event)` rather than at module level.

No need for `kysely-d1` or any extra adapter package. Better Auth uses its built-in `D1SqliteDialect` internally.

### Cloudflare Pages + Nuxt

Nuxt is configured with the `cloudflare-pages` Nitro preset. The D1 binding is accessed via `event.context.cloudflare.env.DB` in server routes.

### Auth Handler

All auth API routes are handled by a single catch-all route at `server/api/auth/[...all].ts`.

### Client

The auth client is created with `better-auth/vue` for Vue/Nuxt reactivity support, including `useSession()` with SSR via `useFetch`.

## Project Structure

```
├── app.vue # Root component
├── pages/
│ ├── index.vue # Home page
│ ├── login.vue # Sign in form
│ ├── signup.vue # Sign up form
│ └── dashboard.vue # Protected dashboard
├── middleware/
│ └── auth.global.ts # Auth route guard
├── lib/
│ └── auth-client.ts # Client-side auth
├── server/
│ ├── lib/
│ │ └── auth.ts # Server-side auth config
│ └── api/
│ ├── auth/[...all].ts # Auth catch-all handler
│ └── me.get.ts # Example protected API route
├── migrations/
│ └── schema.sql # Generated by `npx auth generate`
├── nuxt.config.ts
└── wrangler.toml # Cloudflare config
```
5 changes: 5 additions & 0 deletions examples/nuxt-d1-cloudflare/app.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<template>
<NuxtLayout>
<NuxtPage />
</NuxtLayout>
</template>
3 changes: 3 additions & 0 deletions examples/nuxt-d1-cloudflare/lib/auth-client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { createAuthClient } from 'better-auth/vue'

export const authClient = createAuthClient()
17 changes: 17 additions & 0 deletions examples/nuxt-d1-cloudflare/middleware/auth.global.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { authClient } from '~/lib/auth-client'

export default defineNuxtRouteMiddleware(async (to) => {
if (!import.meta.client) {

@cubic-dev-ai cubic-dev-ai Bot Mar 24, 2026

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: The new client-only early return disables auth checks during SSR, so protected /dashboard routes are no longer enforced server-side.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At examples/nuxt-d1-cloudflare/middleware/auth.global.ts, line 4:

<comment>The new client-only early return disables auth checks during SSR, so protected `/dashboard` routes are no longer enforced server-side.</comment>

<file context>
@@ -1,9 +1,13 @@
 import { authClient } from '~/lib/auth-client'
 
 export default defineNuxtRouteMiddleware(async (to) => {
+  if (!import.meta.client) {
+    return
+  }
</file context>
Fix with Cubic

return
}

const { data: session } = await authClient.useSession(useFetch)

if (!session.value && to.path.startsWith('/dashboard')) {
return navigateTo('/login')
}

if (session.value && (to.path === '/login' || to.path === '/signup')) {
return navigateTo('/dashboard')
}
})
Empty file.
12 changes: 12 additions & 0 deletions examples/nuxt-d1-cloudflare/nuxt.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
export default defineNuxtConfig({
compatibilityDate: '2025-03-24',

nitro: {
preset: 'cloudflare-pages',
},

runtimeConfig: {
betterAuthSecret: process.env.BETTER_AUTH_SECRET || '',
betterAuthUrl: process.env.BETTER_AUTH_URL || 'http://localhost:3000',
},
})
26 changes: 26 additions & 0 deletions examples/nuxt-d1-cloudflare/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"name": "nuxt-d1-cloudflare-example",
"private": true,
"type": "module",
"scripts": {
"dev": "nuxt dev --dotenv .env",
"build": "nuxt build",
"preview": "wrangler pages dev",
"deploy": "wrangler pages deploy",
"db:generate": "npx auth generate --output ./migrations/schema.sql",
"db:migrate": "wrangler d1 execute better-auth-db --local --file=./migrations/schema.sql",
"db:migrate:remote": "wrangler d1 execute better-auth-db --remote --file=./migrations/schema.sql",
"postinstall": "nuxt prepare"
},
"dependencies": {
"better-auth": "^1.2.0",
"nuxt": "^3.16.0",
"vue": "^3.5.0",
"vue-router": "^4.5.0"
},
"devDependencies": {
"@cloudflare/workers-types": "^4.20250313.0",
"typescript": "^5.8.0",
"wrangler": "^4.6.0"
}
}
27 changes: 27 additions & 0 deletions examples/nuxt-d1-cloudflare/pages/dashboard.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<script setup lang="ts">
import { authClient } from '~/lib/auth-client'

const { data: session } = await authClient.useSession(useFetch)

async function handleSignOut() {
await authClient.signOut()
await navigateTo('/')
}
</script>

<template>
<div style="max-width: 600px; margin: 40px auto; font-family: sans-serif;">
<h1>Dashboard</h1>

<div v-if="session">
<p>Signed in as <strong>{{ session.user.email }}</strong></p>

<h2>Session Info</h2>
<pre style="background: #f4f4f4; padding: 16px; border-radius: 4px; overflow-x: auto;">{{ JSON.stringify(session, null, 2) }}</pre>

<button style="padding: 8px 16px; margin-top: 16px;" @click="handleSignOut">
Sign Out
</button>
</div>
</div>
</template>
23 changes: 23 additions & 0 deletions examples/nuxt-d1-cloudflare/pages/index.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<script setup lang="ts">
import { authClient } from '~/lib/auth-client'

const { data: session } = await authClient.useSession(useFetch)
</script>

<template>
<div style="max-width: 600px; margin: 40px auto; font-family: sans-serif;">
<h1>Better Auth + Nuxt + Cloudflare D1</h1>
<p>A minimal example of using Better Auth with Nuxt on Cloudflare Pages with D1 database.</p>

<div v-if="session">
<p>Welcome, <strong>{{ session.user.name }}</strong>!</p>
<NuxtLink to="/dashboard">Go to Dashboard</NuxtLink>
</div>
<div v-else>
<p>
<NuxtLink to="/login">Sign In</NuxtLink> |
<NuxtLink to="/signup">Sign Up</NuxtLink>
</p>
</div>
</div>
</template>
54 changes: 54 additions & 0 deletions examples/nuxt-d1-cloudflare/pages/login.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<script setup lang="ts">
import { authClient } from '~/lib/auth-client'

const email = ref('')
const password = ref('')
const error = ref('')
const loading = ref(false)

async function handleSignIn() {
error.value = ''
loading.value = true

const { error: signInError } = await authClient.signIn.email({
email: email.value,
password: password.value,
})

loading.value = false

if (signInError) {
error.value = signInError.message ?? 'Sign in failed'
return
}

await navigateTo('/dashboard')
}
</script>

<template>
<div style="max-width: 400px; margin: 40px auto; font-family: sans-serif;">
<h1>Sign In</h1>

<form @submit.prevent="handleSignIn">
<div style="margin-bottom: 12px;">
<label for="email">Email</label><br>
<input id="email" v-model="email" type="email" required style="width: 100%; padding: 8px;">
</div>
<div style="margin-bottom: 12px;">
<label for="password">Password</label><br>
<input id="password" v-model="password" type="password" required style="width: 100%; padding: 8px;">
</div>

<p v-if="error" style="color: red;">{{ error }}</p>

<button type="submit" :disabled="loading" style="padding: 8px 16px;">
{{ loading ? 'Signing in...' : 'Sign In' }}
</button>
</form>

<p style="margin-top: 16px;">
Don't have an account? <NuxtLink to="/signup">Sign Up</NuxtLink>
</p>
</div>
</template>
60 changes: 60 additions & 0 deletions examples/nuxt-d1-cloudflare/pages/signup.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<script setup lang="ts">
import { authClient } from '~/lib/auth-client'

const name = ref('')
const email = ref('')
const password = ref('')
const error = ref('')
const loading = ref(false)

async function handleSignUp() {
error.value = ''
loading.value = true

const { error: signUpError } = await authClient.signUp.email({

@cubic-dev-ai cubic-dev-ai Bot Mar 24, 2026

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Handle thrown signup errors with try/catch/finally so loading state is always cleared and failures are shown to the user.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At examples/nuxt-d1-cloudflare/pages/signup.vue, line 14:

<comment>Handle thrown signup errors with `try/catch/finally` so loading state is always cleared and failures are shown to the user.</comment>

<file context>
@@ -0,0 +1,60 @@
+  error.value = ''
+  loading.value = true
+
+  const { error: signUpError } = await authClient.signUp.email({
+    name: name.value,
+    email: email.value,
</file context>
Fix with Cubic

name: name.value,
email: email.value,
password: password.value,
})

loading.value = false

if (signUpError) {
error.value = signUpError.message ?? 'Sign up failed'
return
}

await navigateTo('/dashboard')
}
</script>

<template>
<div style="max-width: 400px; margin: 40px auto; font-family: sans-serif;">
<h1>Sign Up</h1>

<form @submit.prevent="handleSignUp">
<div style="margin-bottom: 12px;">
<label for="name">Name</label><br>
<input id="name" v-model="name" type="text" required style="width: 100%; padding: 8px;">
</div>
<div style="margin-bottom: 12px;">
<label for="email">Email</label><br>
<input id="email" v-model="email" type="email" required style="width: 100%; padding: 8px;">
</div>
<div style="margin-bottom: 12px;">
<label for="password">Password</label><br>
<input id="password" v-model="password" type="password" required minlength="8" style="width: 100%; padding: 8px;">
</div>

<p v-if="error" style="color: red;">{{ error }}</p>

<button type="submit" :disabled="loading" style="padding: 8px 16px;">
{{ loading ? 'Signing up...' : 'Sign Up' }}
</button>
</form>

<p style="margin-top: 16px;">
Already have an account? <NuxtLink to="/login">Sign In</NuxtLink>
</p>
</div>
</template>
6 changes: 6 additions & 0 deletions examples/nuxt-d1-cloudflare/server/api/auth/[...all].ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { getAuth } from '~/server/lib/auth'

export default defineEventHandler((event) => {
const auth = getAuth(event)
return auth.handler(toWebRequest(event))
})
Loading
Loading