-
Notifications
You must be signed in to change notification settings - Fork 0
docs: add Nuxt + Cloudflare Pages + D1 example #8
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
amondnet
wants to merge
2
commits into
main
Choose a base branch
from
amondnet/freckle-ear
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
| ``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| <template> | ||
| <NuxtLayout> | ||
| <NuxtPage /> | ||
| </NuxtLayout> | ||
| </template> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| import { createAuthClient } from 'better-auth/vue' | ||
|
|
||
| export const authClient = createAuthClient() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) { | ||
| 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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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', | ||
| }, | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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" | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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({ | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. P2: Handle thrown signup errors with Prompt for AI agents |
||
| 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> | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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)) | ||
| }) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
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
/dashboardroutes are no longer enforced server-side.Prompt for AI agents