better-auth-cloudflare

0.3.0 · active · verified Wed Apr 22

better-auth-cloudflare is a plugin designed to seamlessly integrate the Better Auth library with the Cloudflare ecosystem, including Workers, D1, Hyperdrive, KV, R2, and geolocation services. It is currently at version 0.3.0 and actively maintained with a continuous release cadence, addressing new features and compatibility updates. This library differentiates itself by providing out-of-the-box support for Cloudflare's serverless offerings, allowing developers to leverage D1 (SQLite), Postgres, and MySQL (via Drizzle ORM or native D1), KV for session caching, and R2 for file storage. It also automatically enriches user sessions with Cloudflare's geolocation and IP detection data, offering a comprehensive solution for authentication in Cloudflare environments without extensive manual setup, making it ideal for Hono, OpenNextJS, and other Worker-compatible frameworks.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to integrate `better-auth-cloudflare` into a Cloudflare Worker using Hono, connecting to D1, KV, and R2 bindings, and accessing user session data including geolocation.

import { withCloudflare } from 'better-auth-cloudflare';
import { BetterAuth } from 'better-auth';
import { Hono } from 'hono';
import { Env } from './env'; // Assume a types file for Cloudflare Bindings

// Initialize the core BetterAuth instance
const auth = new BetterAuth({
    secret: process.env.AUTH_SECRET ?? 'super-secret-key-please-change',
    // ... other better-auth configuration like adapters, providers
});

// Create a Hono app, assuming it's your Cloudflare Worker entry point
const app = new Hono<{ Bindings: Env }>();

// Integrate BetterAuth with Cloudflare services using `withCloudflare`
const cloudflareAuth = withCloudflare(auth, {
    // Use the D1Database binding directly (new in v0.3.0)
    d1Native: (env) => env.D1_DATABASE,
    // Optional: Cloudflare KV for secondary storage/caching
    kv: (env) => env.KV_STORAGE,
    // Optional: Cloudflare R2 for file storage
    r2: (env) => env.R2_BUCKET,
    // Cloudflare-specific configurations are passed here
});

// Mount the better-auth routes to your Hono application
app.route('/auth', cloudflareAuth.router);

// Example route demonstrating session and geolocation access
app.get('/', (c) => {
    const session = cloudflareAuth.getSession(c);
    const user = session?.user;
    const geolocation = session?.geolocation;

    const message = user
        ? `Hello ${user.name} from ${geolocation?.city}, ${geolocation?.country}!`
        : 'Hello, guest! Please log in.';

    return c.text(message);
});

// Export the Hono app for Cloudflare Workers
export default app;

view raw JSON →