nuxt-betterauth-cf
v1.0.23
Published
Nuxt, Better Auth and Cloudflare π₯
Readme
Nuxt, Better Auth and Cloudflare D1
Add Better Auth to you Nuxt project powered by Cloudflare with ease.
Features
- β° Β Easy setup, minimal configuration
- π Β Integrates D1 and KV
- π² Β Manage schemas Drizzle
Quick Setup
Install the module to your Nuxt application with one command:
npx nuxi module add nuxt-betterauth-cfInstall the dependencies in your project.
pnpm add -D drizzle-kit wrangler @cloudflare/workers-types
pnpm add drizzle-kit better-authAdd this to your package.json file
{
// ...
"scripts": {
// ...
"db:generate": "pnpm drizzle-kit generate",
"db:migrate": "wrangler d1 migrations apply <your app name> --local",
"auth:generate": "pnpx @better-auth/cli generate --output ./db/schemas/auth.ts"
}
}Create a wrangler.jsonc or wranger.toml file in the root of your project:
https://developers.cloudflare.com/workers/wrangler/configuration/
The module automatically creates these files in your project:
.
βββ auth
β βββ config.ts
βββ db
β βββ schemas
β βββ app.ts
β βββ auth.ts
β βββ index.ts
βββ drizzle.config.ts
βββ lib
βββ auth.tsConfiguration
The module is somewhat opinionated in terms of how Cloudflare D1 and Cloudflare KV is integrated.
To setup modules, hooks etc. for Better Auth, go to the auth/config.ts file.
From here you can centrally manage your server- and client side configuration.
It's important that the file exports a config and client.
import { defineAuthConfig, defineAuthClientConfig } from 'nuxt-betterauth-cf/config'
import { username } from "better-auth/plugins"
import { usernameClient } from "better-auth/client/plugins"
export const config = defineAuthConfig({
plugins: [username()]
})
export const client = defineAuthClientConfig({
plugins: [usernameClient()]
})Composables
This module comes with a useAuth composable for easy interaction with Better Auth.
Please infer the return type to see the different helpers provided by the composable.
You can always access the raw Better Auth client through .client.
<script setup lang="ts">
const auth = useAuth()
const client = auth.client // Maps to the raw Better Auth client
</script>Server routes
This module automatically adds the api endpoint required by Better Auth.
If you want to setup protected routes you can use the defineAuthenticatedEventHandler.
It's auto-imported for you and works the same as defineEventHandler with the difference that it checks for a valid Better Auth session or throws and error.
The current session and Better Auth instance is provided through the event.context.
export default defineAuthenticatedEventHandler(async (event) => {
const session = event.context.session // The current session
const auth = event.context.auth // The Better Auth instance
})Credits
Inspired by atinux/nuxthub-better-auth
