Better Auth in Astro on Cloudflare Workers

By

Tagged: Astro

Better Auth setup for Astro SSR on Cloudflare Workers: D1 Drizzle adapter, catch-all auth route, session in middleware, no Node dependencies.

I needed auth in an Astro SSR app I built on Cloudflare Workers with D1, and Better Auth fit right in.

It stores sessions in SQLite, runs on plain fetch, and doesn’t need any Node APIs, which matters because Astro on the Cloudflare adapter runs inside workerd instead of Node.

Create the auth instance

Better Auth needs a database adapter, and here we’ll use Drizzle with D1.

Wrap the setup in a factory function that takes your env vars and the D1 binding, and returns an auth instance:

import { betterAuth } from 'better-auth'
import { drizzleAdapter } from 'better-auth/adapters/drizzle'
import { createDb, schema } from '../db'

export function createAuth(env: AuthEnv) {
  const db = createDb(env.DB)

  return betterAuth({
    secret: env.BETTER_AUTH_SECRET,
    baseURL: env.BETTER_AUTH_URL,
    database: drizzleAdapter(db, {
      provider: 'sqlite',
      schema: {
        user: schema.user,
        session: schema.session,
        account: schema.account,
        verification: schema.verification,
      },
    }),
    emailAndPassword: { enabled: true },
  })
}

Better Auth manages the user, session, account, and verification tables, which you map to your Drizzle schema.

Keep createAuth() in a single file so every route and middleware can import the same factory.

The catch-all API route

Better Auth exposes a bunch of endpoints for sign-in, sign-up, OAuth callbacks, and session refresh, and you don’t want a separate Astro file for each one.

Instead, use Astro’s rest parameters so a single catch-all file handles every auth path:

import type { APIRoute } from 'astro'
import { createAuth } from '../../../lib/auth'

export const ALL: APIRoute = async (context) => {
  const auth = createAuth(getEnv())
  return auth.handler(context.request)
}

Save this at src/pages/api/auth/[...all].ts.

Requests to /api/auth/sign-in/email, /api/auth/callback/github, and the rest all hit this route, which forwards the raw Request to auth.handler().

Read the session in middleware

Most pages need to know who’s logged in, so it’s much cleaner to check the session once in Astro middleware:

import { defineMiddleware } from 'astro:middleware'
import { createAuth } from './lib/auth'

export const onRequest = defineMiddleware(async (context, next) => {
  const auth = createAuth(getEnv())

  const sessionData = await auth.api.getSession({
    headers: context.request.headers,
  })

  context.locals.user = sessionData?.user ?? null
  context.locals.session = sessionData?.session ?? null

  return next()
})

Now every .astro page and API route can read context.locals.user.

Protecting routes then comes down to a quick prefix check: if the path starts with /dashboard and there’s no user, redirect to /login.

Why workerd is a good fit

A lot of auth libraries assume you’re running on Node and pull in crypto, fs, or native modules. Better Auth targets Web Crypto and fetch instead, which is the exact same surface area Cloudflare Workers already give you.

Since D1 is SQLite, Better Auth’s Drizzle adapter speaks it natively without any Postgres-only assumptions.

You also get the same runtime locally as you do in production. Running astro dev with the Cloudflare adapter executes inside workerd too, so the auth code you test locally behaves the same way after you deploy.

One gotcha with Astro cookies

Better Auth attaches session cookies directly to its Response object, and sometimes Astro’s cookie helpers miss those Set-Cookie headers when you redirect after sign-in.

You can work around this with a small helper that copies Set-Cookie from the auth response onto your redirect:

export function redirectWithAuthResponse(response: Response, location: string) {
  const headers = new Headers({ Location: location })
  for (const [key, value] of response.headers.entries()) {
    if (key.toLowerCase() === 'set-cookie') headers.append('set-cookie', value)
  }
  return new Response(null, { status: 302, headers })
}

Use this whenever a form POST hits your own route and you’re calling Better Auth’s API directly.

GitHub OAuth

Email and password auth is plenty to get started, and adding GitHub OAuth only takes one config block:

socialProviders: {
  github: {
    clientId: env.GITHUB_CLIENT_ID,
    clientSecret: env.GITHUB_CLIENT_SECRET,
  },
},

Make sure BETTER_AUTH_URL is set to your public origin, since OAuth redirect URLs have to match it exactly.

Because Better Auth runs inside Astro on workerd, you don’t need a separate auth server or Node runtime.

If you’d rather roll your own email/password auth with Web Crypto and D1 instead of using a library, I wrote a walkthrough for that too: native email/password authentication on Cloudflare Workers.

Want me to talk about your product? You can sponsor this site.

Related posts about astro: