clerkMiddleware()Astro Icon grants you access to user authentication state throughout your app. It also allows you to protect specific routes from unauthenticated users. 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 alongside .env.
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 for routes. See the clerkMiddleware() referenceAstro Icon to learn how to require authentication for specific routes.
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:
<SignedIn>: Children of this component can only be seen while signed in.
<SignedOut>: Children of this component can only be seen while signed out.
<UserButton />: Shows the signed-in user's avatar. Selecting it opens a dropdown menu with account management options.
---import { SignedIn, SignedOut, UserButton, SignInButton, SignUpButton,} from'@clerk/astro/components'---<!doctypehtml><htmllang="en"> <head> <metacharset="UTF-8" /> <metaname="viewport"content="width=device-width" /> <linkrel="icon"type="image/svg+xml"href="/favicon.svg" /> <metaname="generator"content={Astro.generator} /> <title>Astro Basics</title> </head> <body> <header> {/* Show the sign-in and sign-up buttons when the user is signed out */} <SignedOut> <SignInButtonmode="modal" /> <SignUpButtonmode="modal" /> </SignedOut> {/* Show the user button when the user is signed in */} <SignedIn> <UserButton /> </SignedIn> </header> <slot /> </body></html>8 lines collapsed<style>html,body {margin:0;width:100%;height:100%; }</style>
Then, use the layout on your homepage:
src/pages/index.astro
---import Layout from'../layouts/Layout.astro'import { SignedIn, SignedOut } from'@clerk/astro/components'---<Layouttitle="Clerk + Astro"> <SignedOut> <p>Sign in to try Clerk out!</p> </SignedOut> <SignedIn> <p>You are signed in!</p> </SignedIn></Layout>