🔥 All-Access Pass — $199 USD (Regular $499) · Unlock all 2,836 Astro themes ➔
komal.nakrani
Get All-Access Pass ($199)
ThemesCategoriesDocsBlogTips & TricksPricingGet All-Access Pass ($199)
Server Rendering••By Komal Nakrani

Astro Authentication: 7 Options Compared for 2026

Astro authentication options compared: Better Auth, Clerk, Auth.js, Supabase Auth, Firebase, Astro sessions and edge protection, with code and trade-offs.

#Astro#Authentication#Middleware#Sessions#Server Rendering

Astro authentication needs a server: install an adapter, render protected pages on demand, and check the user in middleware before the page runs. The most common libraries are Better Auth and Auth.js (self-hosted, open source), Clerk (managed), and Supabase or Firebase Auth (part of a backend platform). For a simple password gate, Astro’s built-in sessions or an edge rule at your host may be all you need.

This guide compares seven options, shows the minimum code for each, and helps you pick one for your Astro 7 project.

Key Takeaways

  • Real login requires on-demand rendering. A fully static site can only hide content in the browser, which is not security.
  • Protect routes in src/middleware.ts and put the user on context.locals so every page can read it.
  • Better Auth suits teams that want to own their user data; Clerk suits teams that want hosted login screens and user management.
  • Pick Supabase or Firebase Auth when you already use that platform for your database.
  • For staging sites or a single shared password, an edge rule or middleware with basic auth is simpler than a full auth library.

What authentication in Astro actually requires

Astro builds static HTML by default. Static files are the same for every visitor, so there’s nothing to check a login against. To have pages that differ per user, you need:

  1. An adapter, such as @astrojs/node, @astrojs/cloudflare, @astrojs/netlify or @astrojs/vercel, so Astro can run code per request.
  2. On-demand routes for protected pages, with export const prerender = false or output: 'server' in the config.
  3. A way to read the session, usually a cookie, in middleware or the page frontmatter.

Public pages can stay prerendered. Most real sites mix the two: a static marketing site and blog, plus a server-rendered /account/ or /dashboard/ area. The Astro SSR guide explains how to set that up, and the adapters explainer covers which adapter to choose.

The shared pattern: middleware plus locals

Every option below ends up in the same shape. Middleware reads the session, puts the user on locals, and redirects anonymous visitors away from protected paths:

// src/middleware.ts
import { defineMiddleware } from 'astro:middleware';
import { getUserFromRequest } from './lib/auth';

const PROTECTED = ['/account', '/dashboard'];

export const onRequest = defineMiddleware(async (context, next) => {
  context.locals.user = await getUserFromRequest(context.request, context.cookies);

  const needsAuth = PROTECTED.some((p) => context.url.pathname.startsWith(p));
  if (needsAuth && !context.locals.user) {
    return context.redirect(`/login/?next=${encodeURIComponent(context.url.pathname)}`);
  }
  return next();
});
// src/env.d.ts
declare namespace App {
  interface Locals {
    user: { id: string; email: string } | null;
  }
}

Pages then read Astro.locals.user. Only getUserFromRequest changes between libraries. The middleware guide covers ordering and sequence().

1. Better Auth

Better Auth is an open-source TypeScript auth library that runs inside your app and stores users in your own database. It supports email and password, OAuth providers, sessions, and plugins for things like two-factor auth and organizations.

// src/lib/auth.ts
import { betterAuth } from 'better-auth';
import Database from 'better-sqlite3';

export const auth = betterAuth({
  database: new Database('./auth.db'),
  emailAndPassword: { enabled: true },
  socialProviders: {
    github: {
      clientId: import.meta.env.GITHUB_CLIENT_ID,
      clientSecret: import.meta.env.GITHUB_CLIENT_SECRET,
    },
  },
});
// src/pages/api/auth/[...all].ts
import type { APIRoute } from 'astro';
import { auth } from '../../../lib/auth';

export const prerender = false;
export const ALL: APIRoute = (ctx) => auth.handler(ctx.request);

In middleware, call auth.api.getSession({ headers: context.request.headers }) to get the user. Choose it if you want no per-user fees, full control of the user table, and don’t mind running a database.

2. Clerk

Clerk is a hosted authentication service with an official Astro SDK, @clerk/astro. It provides prebuilt sign-in and user-profile components, social logins, multi-factor auth and an admin dashboard.

// astro.config.mjs
import { defineConfig } from 'astro/config';
import node from '@astrojs/node';
import clerk from '@clerk/astro';

export default defineConfig({
  integrations: [clerk()],
  adapter: node({ mode: 'standalone' }),
  output: 'server',
});
// src/middleware.ts
import { clerkMiddleware, createRouteMatcher } from '@clerk/astro/server';

const isProtected = createRouteMatcher(['/dashboard(.*)']);

export const onRequest = clerkMiddleware((auth, context) => {
  if (isProtected(context.request) && !auth().userId) {
    return auth().redirectToSignIn();
  }
});

Choose it if you want login working in an afternoon and are comfortable with a managed service and its pricing as you grow. Check Clerk’s current pricing page before committing.

3. Auth.js via auth-astro

Auth.js (formerly NextAuth.js) is a widely used open-source auth library with a large set of OAuth providers. In Astro it’s used through the community auth-astro integration, which adds the routes and a getSession() helper.

npx astro add auth-astro
// auth.config.ts
import GitHub from '@auth/core/providers/github';
import { defineConfig } from 'auth-astro';

export default defineConfig({
  providers: [
    GitHub({
      clientId: import.meta.env.GITHUB_CLIENT_ID,
      clientSecret: import.meta.env.GITHUB_CLIENT_SECRET,
    }),
  ],
});

Choose it if you mainly need OAuth sign-in (GitHub, Google and so on) and already know Auth.js. Because auth-astro is community-maintained, check that its latest release supports your Astro version before you start.

4. Supabase Auth

If your data already lives in Supabase, its auth is the natural choice. Use the @supabase/ssr package so sessions are stored in cookies that Astro can read on the server:

// src/lib/supabase.ts
import { createServerClient, parseCookieHeader } from '@supabase/ssr';
import type { AstroCookies } from 'astro';

export function supabaseServer(request: Request, cookies: AstroCookies) {
  return createServerClient(import.meta.env.SUPABASE_URL, import.meta.env.SUPABASE_ANON_KEY, {
    cookies: {
      getAll: () => parseCookieHeader(request.headers.get('Cookie') ?? ''),
      setAll: (list) => list.forEach(({ name, value, options }) => cookies.set(name, value, options)),
    },
  });
}

Then await supabaseServer(request, cookies).auth.getUser() in middleware. Row-level security in Postgres means the same user identity protects your data, not just your pages. Choose it if you use Supabase for the database anyway.

5. Firebase Authentication

Firebase Auth handles sign-in in the browser with the Firebase client SDK. For server-rendered Astro pages, the common pattern is to exchange the client’s ID token for a session cookie using the Firebase Admin SDK in an endpoint, then verify that cookie in middleware with verifySessionCookie().

It takes more wiring than the options above, because the client and server halves are separate SDKs. Choose it if your app already depends on Firebase services such as Firestore.

6. Astro sessions and cookies, built in

Astro has a built-in session API. With an adapter that provides session storage (or a configured storage driver), Astro.session stores data server-side and keeps only an ID in a cookie:

// src/pages/api/login.ts
import type { APIRoute } from 'astro';
import { verifyPassword } from '../../lib/users';

export const prerender = false;

export const POST: APIRoute = async ({ request, session, redirect }) => {
  const form = await request.formData();
  const user = await verifyPassword(String(form.get('email')), String(form.get('password')));
  if (!user) return redirect('/login/?error=1');

  await session?.regenerate();
  session?.set('userId', user.id);
  return redirect('/account/');
};

regenerate() issues a new session ID on login, which prevents session fixation. session.destroy() logs out. This is fine for a small internal tool, but you are responsible for password hashing, rate limiting and resets. For anything public, a library like Better Auth saves you from writing those pieces. The sessions explainer and the official sessions docs cover storage drivers.

7. Edge protection for staging and private sites

Sometimes “auth” just means keeping a preview site or client draft private. You don’t need user accounts for that:

  • Host-level access rules. Cloudflare Access, Netlify password protection and Vercel deployment protection can put a login in front of a whole site with no code. Availability depends on the plan.
  • Basic auth in middleware. A few lines that check an Authorization header against an environment variable. The basic auth tip has the code.

These work even for static sites when done at the host, because the check happens before the files are served.

Comparison table

Option Hosting model User data stored Good for
Better Auth self-hosted library your database full control, no per-user fees
Clerk managed service Clerk fastest setup, prebuilt UI
Auth.js (auth-astro) self-hosted library your database or JWT OAuth-first apps
Supabase Auth managed platform Supabase Postgres apps already on Supabase
Firebase Auth managed platform Firebase apps already on Firebase
Astro sessions built in your session storage small internal tools
Edge rules / basic auth host or middleware none staging, client previews

How to choose

  1. Is it just a private preview? Use edge protection or basic auth.
  2. Already on Supabase or Firebase? Use their auth.
  3. Want hosted UI and user management? Use Clerk.
  4. Want to own everything and avoid per-user pricing? Use Better Auth.
  5. Only need “Sign in with GitHub”? Auth.js is a reasonable fit.

Whatever you pick, keep secrets in environment variables (the environment variables guide covers astro:env), and leave Astro’s security.checkOrigin on so form posts from other sites are rejected. If you are starting from one of the Astro SaaS themes, note that the theme gives you the marketing site, pricing and docs pages as static HTML; the login and app area are something you add with one of the options above. The Astro config docs show where the adapter and output settings go.

FAQ

Does Astro have built-in authentication?

No full auth system is built in, but Astro provides the building blocks: middleware, cookies, locals and a session API. Most projects add a library such as Better Auth, Clerk or Auth.js for sign-up, OAuth and password handling.

Can I add authentication to a static Astro site?

Not securely in the page code, because static files are the same for everyone. Either render protected pages on demand with an adapter, or protect the whole site at the host with an access rule or password protection.

What is the best authentication library for Astro?

It depends on your constraints. Better Auth is a strong self-hosted default, Clerk is the quickest managed option, and Supabase or Firebase Auth make sense if you already use those platforms. All of them follow the same middleware-and-locals pattern in Astro.

How do I protect a route in Astro?

Render it on demand, then check the user in src/middleware.ts. If there’s no valid session for a protected path, return context.redirect('/login/'). Otherwise store the user on context.locals and call next().

Lucia’s author deprecated the library in 2025 and turned the project into a guide on implementing sessions yourself. It’s still a useful learning resource, but for new projects pick a maintained library or Astro’s built-in sessions.