If you're adding Clerk to an existing app on Astro 4.15+, 5, or 6:
Run npm install @clerk/astro instead, and keep your Astro version and adapter.
If you need an adapter, install the @astrojs/node major that matches your Astro version (v10 for Astro 6, v9 for Astro 5). Don't run npx astro add node — it installs the Astro 7-only latest.
clerkMiddleware()Astro Icon grants you access to user authentication state throughout your app. To add clerkMiddleware() to your app, follow these steps:
Create a middleware.ts file.
If you're using the /src directory, create middleware.ts in the /src directory.
If you're not using the /src directory, create middleware.ts in the root directory.
In your middleware.ts file, export an onRequest constant and assign the result of the clerkMiddleware() function to it.
src/middleware.ts
By default, clerkMiddleware() will not protect any routes. All routes are public and you must opt-in to protection. To require a signed-in user, protect resources close to where they're used, as shown in the guide on reading user data.
You can control which content signed-in and signed-out users can see with Clerk's prebuilt control components. The following example creates a header using the following components:
---import Layout from'../layouts/Layout.astro'import { Show } from'@clerk/astro/components'---<Layouttitle="Clerk + Astro"> <Showwhen="signed-out"> <p>Sign in to try Clerk out!</p> </Show> <Showwhen="signed-in"> <p>You are signed in!</p> </Show></Layout>
Select "Sign up" on the page and authenticate to create your first user.
Important
To make configuration changes to your Clerk development instance, claim the Clerk keys that were generated for you by selecting Configure your application in the bottom right of your app. This will associate the application with your Clerk account. Once claimed, you can find your Publishable Key and Secret Key any time on the API keys page in the Clerk Dashboard.