To add Better Auth to Astro, install better-auth, create an auth instance with your database and sign-in methods, mount auth.handler on a catch-all endpoint at src/pages/api/auth/[...all].ts, and read the session in middleware with auth.api.getSession(). Users sign up and sign in through Better Auth’s client from the browser, and their records live in your own database. You need an adapter because auth runs per request.
This guide builds a working email-and-password login with Astro 7 and Better Auth, then adds GitHub sign-in and route protection.
Key Takeaways
- Better Auth is an open-source TypeScript auth library that runs inside your Astro app.
- It stores users, sessions and accounts in your database (SQLite, Postgres, MySQL, or through Drizzle, Prisma and Kysely).
- One catch-all endpoint handles every auth route, including OAuth callbacks.
auth.api.getSession({ headers })in middleware puts the user onAstro.locals.- Plugins add two-factor auth, organizations, passkeys and more without a separate service.
Why choose Better Auth for Astro
Better Auth is framework-agnostic: it takes a standard Request and returns a Response, which is exactly what Astro endpoints work with. There’s no hosted service, no per-user fee, and no vendor holding your user table. You run the database and own the data.
| Question | Better Auth answer |
|---|---|
| Where do users live? | Tables in your own database |
| What does it cost? | Free and open source; you pay for your database and hosting |
| Login methods | Email and password, OAuth providers, magic links and passkeys via plugins |
| UI | You build the forms (it’s headless) |
| Server needed? | Yes, an Astro adapter |
The main trade-off against a hosted service like Clerk is that you build the forms and handle email delivery for verification and password resets. If you want hosted screens instead, see our Clerk and Astro guide, and for a wider view, the Astro authentication options comparison.
Install Better Auth and an adapter
npm install better-auth pg
npx astro add node
This guide uses Postgres through pg. Better Auth also accepts a better-sqlite3 or mysql2 connection directly, or an ORM adapter if you already use Drizzle or Prisma. Generate a secret and set the base URL:
# .env
BETTER_AUTH_SECRET=generate-a-long-random-string
BETTER_AUTH_URL=http://localhost:4321
DATABASE_URL=postgres://user:password@localhost:5432/app
openssl rand -base64 32 produces a suitable secret. In production, set BETTER_AUTH_URL to your real origin, such as https://app.example.com.
Make sure the config has an adapter. With the Node adapter it looks like this:
// astro.config.mjs
import { defineConfig } from 'astro/config';
import node from '@astrojs/node';
export default defineConfig({
adapter: node({ mode: 'standalone' }),
});
Pages stay prerendered by default. Auth endpoints and protected pages opt into on-demand rendering with export const prerender = false, so your marketing pages remain static.
Create the auth instance
// src/lib/auth.ts
import { betterAuth } from 'better-auth';
import { Pool } from 'pg';
export const auth = betterAuth({
database: new Pool({ connectionString: import.meta.env.DATABASE_URL }),
emailAndPassword: {
enabled: true,
minPasswordLength: 10,
},
socialProviders: {
github: {
clientId: import.meta.env.GITHUB_CLIENT_ID,
clientSecret: import.meta.env.GITHUB_CLIENT_SECRET,
},
},
});
Better Auth reads BETTER_AUTH_SECRET and BETTER_AUTH_URL from the environment automatically. Now create the tables. The CLI reads your auth file and either creates the tables directly or generates a schema for your ORM:
npx @better-auth/cli migrate
That creates the user, session, account and verification tables. If you use Drizzle or Prisma, run npx @better-auth/cli generate instead and apply the output with your ORM’s migration tool. Re-run the command whenever you add a plugin, since plugins can add columns or tables.
Mount the auth handler
All of Better Auth’s routes (sign-up, sign-in, sign-out, session, OAuth callbacks) live under one path. A catch-all endpoint forwards them:
// src/pages/api/auth/[...all].ts
import type { APIRoute } from 'astro';
import { auth } from '../../../lib/auth';
export const prerender = false;
export const ALL: APIRoute = async (ctx) => {
return auth.handler(ctx.request);
};
ALL handles every HTTP method. /api/auth is Better Auth’s default basePath; if you mount it elsewhere, set basePath in the config to match. Check it works by visiting /api/auth/ok in the dev server, which returns a small JSON response. The Astro API endpoints guide explains catch-all routes and ALL.
Build sign-up and sign-in forms
Better Auth is headless, so you write the forms. Create the client once:
// src/lib/auth-client.ts
import { createAuthClient } from 'better-auth/client';
export const authClient = createAuthClient();
With no baseURL, the client calls the same origin, which is what you want when Astro serves both the pages and /api/auth. Now a sign-in page with a plain form and a small script:
---
// src/pages/sign-in.astro
import BaseLayout from '../layouts/BaseLayout.astro';
---
<BaseLayout title="Sign in">
<h1>Sign in</h1>
<form id="sign-in">
<label>Email <input name="email" type="email" autocomplete="email" required /></label>
<label>Password <input name="password" type="password" autocomplete="current-password" required /></label>
<button>Sign in</button>
<p id="error" role="alert"></p>
</form>
<button id="github" type="button">Continue with GitHub</button>
</BaseLayout>
<script>
import { authClient } from '../lib/auth-client';
const form = document.getElementById('sign-in') as HTMLFormElement;
const errorEl = document.getElementById('error')!;
form.addEventListener('submit', async (event) => {
event.preventDefault();
const data = new FormData(form);
const { error } = await authClient.signIn.email({
email: String(data.get('email')),
password: String(data.get('password')),
});
if (error) errorEl.textContent = error.message ?? 'Sign-in failed.';
else window.location.assign('/dashboard/');
});
document.getElementById('github')?.addEventListener('click', () => {
authClient.signIn.social({ provider: 'github', callbackURL: '/dashboard/' });
});
</script>
The sign-up page is the same form with a name field, calling authClient.signUp.email({ name, email, password }). The page itself can stay prerendered because all the work happens in the browser and the auth endpoint. On success, Better Auth sets an HTTP-only session cookie, so the next request to the server already carries the session. The <script> is bundled by Astro, as described in our script tag guide.
For GitHub, create an OAuth app in GitHub’s developer settings with the callback URL http://localhost:4321/api/auth/callback/github (and your production equivalent), then put its ID and secret in GITHUB_CLIENT_ID and GITHUB_CLIENT_SECRET.
Protect pages in middleware
Middleware reads the session once per request and stores it on locals:
// src/middleware.ts
import { defineMiddleware } from 'astro:middleware';
import { auth } from './lib/auth';
export const onRequest = defineMiddleware(async (context, next) => {
context.locals.user = null;
context.locals.session = null;
if (context.isPrerendered) return next();
const result = await auth.api.getSession({ headers: context.request.headers });
context.locals.user = result?.user ?? null;
context.locals.session = result?.session ?? null;
if (context.url.pathname.startsWith('/dashboard') && !result) {
return context.redirect('/sign-in/');
}
return next();
});
// src/env.d.ts
declare namespace App {
interface Locals {
user: import('better-auth').User | null;
session: import('better-auth').Session | null;
}
}
A protected page then reads Astro.locals.user directly:
---
// src/pages/dashboard/index.astro
export const prerender = false;
const { user } = Astro.locals;
---
<h1>Hello, {user?.name}</h1>
<button id="sign-out">Sign out</button>
<script>
import { authClient } from '../../lib/auth-client';
document.getElementById('sign-out')?.addEventListener('click', async () => {
await authClient.signOut();
window.location.assign('/');
});
</script>
The isPrerendered check skips static pages, which have no request headers at build time. In endpoints, check locals.user as well, so API routes stay protected even if the middleware path list changes. Our Astro middleware guide covers sequence() and ordering if you run more than one middleware.
Verification emails, plugins and production
Email verification and password reset. Better Auth generates the tokens, but you send the email. Provide emailVerification.sendVerificationEmail and emailAndPassword.sendResetPassword functions in the config that call your email provider, and set requireEmailVerification: true if accounts must be verified before signing in.
Plugins. Features beyond the core come as plugins imported from better-auth/plugins: two-factor authentication, organizations and roles, magic links, admin tools and more. Add the server plugin to betterAuth({ plugins: [...] }), the matching client plugin to createAuthClient({ plugins: [...] }), and re-run the CLI to update the schema.
Rate limiting and origins. Better Auth includes rate limiting on its endpoints and checks request origins against BETTER_AUTH_URL. If your frontend and auth API sit on different origins, list them in trustedOrigins.
Hosting. Use an adapter whose runtime can reach your database. With Postgres through pg, the Node, Netlify and Vercel adapters work. On Cloudflare Workers, use a database with an HTTP or Workers-compatible driver, and check Better Auth’s docs for the current setup. The Better Auth Astro integration docs list framework-specific notes.
If you’re building a product with a public site, a technology or SaaS theme gives you the landing, pricing and docs pages, and Better Auth runs the signed-in area behind them.
FAQ
Does Better Auth work with a static Astro site?
Your public pages can stay static, but Better Auth itself needs a server: the /api/auth endpoint, the middleware and protected pages run per request. Add an adapter and set prerender = false only on those routes.
Which database should I use with Better Auth in Astro?
Any database Better Auth supports: Postgres, MySQL and SQLite directly, or through Drizzle, Prisma or Kysely adapters. Pick the one your app already uses. For serverless hosts, a database with a serverless-friendly driver, such as Neon, Supabase or Turso, avoids connection limits.
How do I get the current user in an Astro page with Better Auth?
Call auth.api.getSession({ headers: Astro.request.headers }) on an on-demand page, or do it once in middleware and read Astro.locals.user. It returns null when no one is signed in.
Is Better Auth free?
Yes. Better Auth is open source under the MIT licence and runs in your own app, so there are no per-user fees. Your costs are the database, email delivery and hosting you already pay for.
Can I sign users in from an Astro Action instead of the client?
You can call auth.api.signInEmail() on the server, but you must forward the cookies it sets onto Astro’s response yourself. Calling authClient.signIn.email() from the browser is simpler because the cookie lands directly from the auth endpoint.