How to Use Clerk with Astro: Complete Guide
Step-by-step guide to integrating Clerk authentication with your Astro website. Installation, configuration, and best practices.
Clerk is a complete user management platform with pre-built UI components, social login, multi-factor auth, and organization management. It has an official Astro integration that makes adding authentication to your site surprisingly straightforward. Instead of building login forms and session management from scratch, you drop in Clerk's components and focus on your actual product.
Prerequisites
- Node.js 18+
- An Astro project (
npm create astro@latest) - A Clerk account (free for up to 10,000 monthly active users at clerk.com)
Installation
Install the Clerk Astro SDK:
npm install @clerk/astro
Then add it to your Astro config:
// astro.config.mjs
import { defineConfig } from "astro/config";
import clerk from "@clerk/astro";
export default defineConfig({
output: "server",
integrations: [clerk()],
});
Clerk requires server-side rendering, so set output to server or hybrid.
Configuration
Get your API keys from the Clerk dashboard. Go to your application, then API Keys.
Add them to your .env file:
PUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_xxxxxxxxxxxxx
CLERK_SECRET_KEY=sk_test_xxxxxxxxxxxxx
PUBLIC_CLERK_SIGN_IN_URL=/sign-in
PUBLIC_CLERK_SIGN_UP_URL=/sign-up
Basic Usage
Clerk provides pre-built React components for sign-in, sign-up, and user management. Here is a sign-in page:
---
// src/pages/sign-in.astro
import { SignIn } from "@clerk/astro/components";
import BaseLayout from "../layouts/BaseLayout.astro";
---
<BaseLayout title="Sign In">
<main class="flex items-center justify-center min-h-screen">
<SignIn client:load />
</main>
</BaseLayout>
And a sign-up page:
---
// src/pages/sign-up.astro
import { SignUp } from "@clerk/astro/components";
import BaseLayout from "../layouts/BaseLayout.astro";
---
<BaseLayout title="Sign Up">
<main class="flex items-center justify-center min-h-screen">
<SignUp client:load />
</main>
</BaseLayout>
Note the client:load directive. Clerk components are interactive and need client-side hydration.
Protecting Routes
Use Clerk's middleware to protect pages that require authentication:
// src/middleware.ts
import { clerkMiddleware, createRouteMatcher } from "@clerk/astro/server";
const isProtectedRoute = createRouteMatcher(["/dashboard(.*)", "/settings(.*)"]);
export const onRequest = clerkMiddleware((auth, context) => {
const { userId } = auth();
if (isProtectedRoute(context.request) && !userId) {
return context.redirect("/sign-in");
}
});
Accessing User Data
In any server-rendered page, access the current user from Astro.locals:
---
// src/pages/dashboard.astro
export const prerender = false;
import BaseLayout from "../layouts/BaseLayout.astro";
const { userId } = Astro.locals.auth();
if (!userId) {
return Astro.redirect("/sign-in");
}
const response = await fetch(`https://api.clerk.com/v1/users/${userId}`, {
headers: {
Authorization: `Bearer ${import.meta.env.CLERK_SECRET_KEY}`,
},
});
const user = await response.json();
---
<BaseLayout title="Dashboard">
<main class="max-w-4xl mx-auto py-12">
<h1>Welcome, {user.first_name}!</h1>
<p>Email: {user.email_addresses[0]?.email_address}</p>
</main>
</BaseLayout>
Adding User Profile Management
Clerk has a pre-built user profile component:
---
// src/pages/settings.astro
export const prerender = false;
import { UserProfile } from "@clerk/astro/components";
import BaseLayout from "../layouts/BaseLayout.astro";
---
<BaseLayout title="Settings">
<main class="max-w-4xl mx-auto py-12">
<UserProfile client:load />
</main>
</BaseLayout>
This renders a full profile management UI where users can update their name, email, password, connected accounts, and active sessions.
Navigation with Auth State
Show different navigation items based on whether the user is signed in:
---
// src/components/Header.astro
import { SignedIn, SignedOut, UserButton } from "@clerk/astro/components";
---
<header class="flex items-center justify-between p-4">
<a href="/" class="text-xl font-bold">My Site</a>
<nav class="flex items-center gap-4">
<SignedIn client:load>
<a href="/dashboard">Dashboard</a>
<UserButton client:load />
</SignedIn>
<SignedOut client:load>
<a href="/sign-in">Sign In</a>
<a href="/sign-up" class="bg-blue-600 text-white px-4 py-2 rounded">
Sign Up
</a>
</SignedOut>
</nav>
</header>
Production Tips
Use the
client:loaddirective for Clerk components. They need to hydrate immediately for auth state to show. Usingclient:visibleorclient:idlecan cause layout shifts as components pop in late.Configure social login providers in the Clerk dashboard. Adding Google, GitHub, or Apple sign-in takes about two minutes per provider. No code changes needed.
Set up webhooks for user events. Clerk can send webhooks when users sign up, update their profile, or delete their account. Use these to sync user data with your database.
Customize the Clerk appearance. Pass a custom theme to match your brand colors and typography. Clerk components support deep customization through their
appearanceprop.Use organizations for team features. Clerk's organization management lets users create teams, invite members, and assign roles. All built-in, no custom code needed.
Alternatives to Consider
- Lucia if you want a lightweight, self-hosted auth library with full control over the implementation. More work, but no vendor lock-in.
- Supabase Auth if you are already using Supabase for your database. Auth is built in and free.
- Auth0 if you need enterprise features like SSO, compliance certifications, and advanced security policies.
Wrapping Up
Clerk is the fastest way to add production-ready authentication to an Astro site. The pre-built components handle the UI, the middleware handles route protection, and the dashboard handles configuration. You can go from zero to fully authenticated app in under an hour.
Related Articles
How to Use Algolia with Astro: Complete Guide
Step-by-step guide to integrating Algolia with your Astro website.
How to Integrate Auth0 with Astro: Complete Guide
Step-by-step guide to integrating Auth0 with your Astro website. Setup, configuration, and best practices.
How to Use AWS Amplify with Astro: Complete Guide
Step-by-step guide to integrating AWS Amplify with your Astro website.