🔥 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)
CMS & Integrations••By Komal Nakrani

Astro Clerk Authentication: Setup, Middleware and Roles

Add Clerk authentication to Astro: install @clerk/astro, protect routes with clerkMiddleware, read users in pages and endpoints, and sync users with webhooks.

#Astro#Clerk#Authentication#Middleware

To add Clerk authentication to Astro, run npx astro add @clerk/astro, add your publishable and secret keys to .env, install a server adapter, and export clerkMiddleware() from src/middleware.ts. Clerk then hosts sign-in, sign-up and user management, its components render the login buttons and user menu, and Astro.locals.auth() tells any page or endpoint who is signed in.

This guide sets up Clerk on Astro 7 from install to protected routes, roles and webhooks.

Key Takeaways

  • @clerk/astro is Clerk’s official Astro SDK: an integration, middleware, components and helpers.
  • Clerk needs on-demand rendering, so add an adapter; marketing pages can still be prerendered.
  • Protect routes once in middleware with createRouteMatcher() and redirectToSignIn().
  • Read the user server-side with Astro.locals.auth() and Astro.locals.currentUser().
  • Use Clerk webhooks, verified with Svix, to copy users into your own database.

When Clerk is the right choice

Clerk is a hosted authentication and user management service. You get prebuilt sign-in and sign-up flows, social logins, passkeys, multi-factor authentication, organizations with roles, and a dashboard for managing users, without storing passwords yourself.

The trade-off is that your user records live in Clerk, and pricing grows with monthly active users beyond the free tier. Check Clerk’s current pricing page before you commit. If you’d rather keep users in your own database, look at Better Auth with Astro or the other options in our Astro authentication comparison.

You want Clerk fit
Login working in an afternoon Strong: prebuilt UI and hosted flows
Social login, MFA, passkeys Built in, toggled in the dashboard
Teams and roles (B2B SaaS) Organizations with roles and permissions
Users in your own Postgres Possible via webhooks, but Clerk stays the source of truth
A fully static site Not a fit: Clerk needs a server

Install @clerk/astro

Create an application in the Clerk dashboard and copy its keys into .env:

# .env
PUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_...
CLERK_SECRET_KEY=sk_test_...

The publishable key is safe in the browser; the secret key must stay on the server and in your host’s environment settings. Then add the integration and an adapter:

npx astro add @clerk/astro
npx astro add node

Your config ends up like this:

// 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',
});

Swap @astrojs/node for the Netlify, Vercel or Cloudflare adapter to match your host. With output: 'server', pages render on demand by default. Pages that never depend on the user, such as the homepage, pricing or blog posts, can opt back into static output with export const prerender = true. Our Astro adapters guide explains how adapters and prerendering interact.

Add the middleware

clerkMiddleware() reads the session on each request and makes locals.auth() available. Pass a callback to protect routes:

// src/middleware.ts
import { clerkMiddleware, createRouteMatcher } from '@clerk/astro/server';

const isProtectedRoute = createRouteMatcher(['/dashboard(.*)', '/account(.*)']);

export const onRequest = clerkMiddleware((auth, context) => {
  const { userId, redirectToSignIn } = auth();

  if (!userId && isProtectedRoute(context.request)) {
    return redirectToSignIn();
  }
});

createRouteMatcher() takes path patterns, so /dashboard(.*) covers /dashboard/ and everything below it. redirectToSignIn() sends the visitor to Clerk’s sign-in page and returns them to the original URL afterwards. If you have other middleware, combine them with sequence() from astro:middleware, with Clerk’s first so later middleware can call locals.auth(). The Astro middleware guide covers ordering.

Add sign-in buttons and the user menu

@clerk/astro/components ships Astro components for the common UI. A header that switches between a sign-in button and the user menu:

---
// src/components/Header.astro
import { SignedIn, SignedOut, SignInButton, UserButton } from '@clerk/astro/components';
---
<header>
  <a href="/">Acme</a>
  <nav>
    <a href="/pricing/">Pricing</a>
    <SignedOut>
      <SignInButton mode="modal" />
    </SignedOut>
    <SignedIn>
      <a href="/dashboard/">Dashboard</a>
      <UserButton />
    </SignedIn>
  </nav>
</header>

mode="modal" opens sign-in in an overlay; without it, the button goes to Clerk’s hosted Account Portal. For a dedicated page, render <SignIn /> and <SignUp /> from the same package on routes like /sign-in/ and set the matching paths in the Clerk dashboard. Clerk occasionally renames or consolidates components between major SDK versions, so check the current @clerk/astro reference if an import fails.

These components load Clerk’s client script, which is the main JavaScript cost of Clerk. Only include the header components on pages where signed-in state matters, and keep fully static pages free of them if you’re chasing a zero-JS marketing site.

Read the user in pages and endpoints

On any on-demand page, Astro.locals.auth() returns the session’s IDs, and Astro.locals.currentUser() fetches the full user object from Clerk:

---
// src/pages/dashboard/index.astro
import BaseLayout from '../../layouts/BaseLayout.astro';

const { userId } = Astro.locals.auth();
const user = await Astro.locals.currentUser();
---
<BaseLayout title="Dashboard">
  <h1>Welcome back, {user?.firstName ?? 'there'}</h1>
  <p>Your user ID is <code>{userId}</code>.</p>
</BaseLayout>

auth() is synchronous and cheap because it reads the verified session token. currentUser() makes an API call to Clerk, so use it only when you need profile fields such as name, email or image.

Endpoints work the same way through locals. Always check userId in the endpoint itself, even if the middleware protects the path, so an API route can’t be reached by accident:

// src/pages/api/projects.ts
import type { APIRoute } from 'astro';
import { getProjectsForUser } from '../../lib/projects';

export const GET: APIRoute = async ({ locals }) => {
  const { userId } = locals.auth();
  if (!userId) return new Response('Unauthorized', { status: 401 });

  const projects = await getProjectsForUser(userId);
  return Response.json(projects);
};

Store the Clerk userId as the owner column in your own tables. It’s stable for the life of the account. The Astro API endpoints guide covers request handling and responses.

Roles, permissions and organizations

For B2B apps, enable Organizations in the Clerk dashboard. Users join organizations with a role (for example org:admin or org:member), and you can define custom permissions. Check them with has():

// src/middleware.ts
import { clerkMiddleware, createRouteMatcher } from '@clerk/astro/server';

const isAdminRoute = createRouteMatcher(['/admin(.*)']);

export const onRequest = clerkMiddleware((auth, context) => {
  const { userId, has, redirectToSignIn } = auth();

  if (isAdminRoute(context.request)) {
    if (!userId) return redirectToSignIn();
    if (!has({ role: 'org:admin' })) {
      return new Response('Forbidden', { status: 403 });
    }
  }
});

auth() also returns orgId for the active organization, which is the value to filter your data by in a multi-tenant app. For simple per-user flags without organizations, store them in the user’s publicMetadata from your backend and read them from the session claims.

Sync users with webhooks

Clerk is the source of truth for users, but you often want a row in your own database, for example to join users to orders. Clerk sends webhooks for events such as user.created, user.updated and user.deleted, signed with Svix. Verify them before trusting the payload:

// src/pages/api/clerk-webhook.ts
import type { APIRoute } from 'astro';
import { Webhook } from 'svix';
import { upsertUser, deleteUser } from '../../lib/users';

export const POST: APIRoute = async ({ request }) => {
  const payload = await request.text();
  const headers = {
    'svix-id': request.headers.get('svix-id') ?? '',
    'svix-timestamp': request.headers.get('svix-timestamp') ?? '',
    'svix-signature': request.headers.get('svix-signature') ?? '',
  };

  let event: { type: string; data: any };
  try {
    event = new Webhook(import.meta.env.CLERK_WEBHOOK_SECRET).verify(payload, headers) as typeof event;
  } catch {
    return new Response('Invalid signature', { status: 400 });
  }

  if (event.type === 'user.created' || event.type === 'user.updated') {
    await upsertUser(event.data.id, event.data.email_addresses?.[0]?.email_address);
  }
  if (event.type === 'user.deleted') {
    await deleteUser(event.data.id);
  }
  return new Response(null, { status: 204 });
};

Install svix with npm install svix, add the endpoint URL in the Clerk dashboard under Webhooks, and copy its signing secret into CLERK_WEBHOOK_SECRET. Read the raw body with request.text(); parsing it first changes the bytes and breaks the signature check. Leave this path unprotected in your middleware matcher, since Clerk’s servers don’t send a session.

Deploying Clerk with Astro

  • Keys per environment. Clerk development instances use pk_test_ and sk_test_ keys; production instances use pk_live_ and sk_live_ and require your own domain with DNS records Clerk lists in the dashboard.
  • Adapters. The Node, Netlify, Vercel and Cloudflare adapters all work. Set both keys in the host’s environment settings for production builds.
  • Static pages. Prerendered pages can’t read locals.auth() at request time. Keep user-specific content on on-demand routes.

If your product needs a marketing site in front of the app, a SaaS or technology theme covers the public pages, and Clerk handles the signed-in area. The official Astro authentication guide also lists Clerk alongside other providers.

FAQ

Does Clerk work with a static Astro site?

Not on its own. Clerk’s middleware and locals.auth() need code running per request, so you need an adapter. You can still prerender pages that don’t depend on the user with export const prerender = true and keep only the signed-in area on demand.

How do I protect a page with Clerk in Astro?

Export clerkMiddleware() from src/middleware.ts, define the protected paths with createRouteMatcher(), and return redirectToSignIn() when auth().userId is missing. For extra safety, also check Astro.locals.auth().userId in sensitive pages and endpoints.

Is Clerk free for Astro projects?

Clerk has a free tier that covers a limited number of monthly active users, with paid plans and add-ons above that. Astro and the @clerk/astro SDK are free. Check Clerk’s pricing page for the current limits, since they change.

Can I use Clerk with React components in Astro?

Yes. @clerk/astro provides Astro components, and Clerk’s React components work inside React islands when the React integration is installed. The Astro SDK also exposes client-side stores for reading auth state in framework components.

Clerk or Better Auth for an Astro app?

Choose Clerk if you want hosted sign-in screens, user management and organizations with little code, and accept per-user pricing as you grow. Choose Better Auth if you want users in your own database with no per-user fees and are fine running and maintaining that database.