Official SDK for Astro

Category
SDK
Published

Our community SDK is all grown up 🧑‍🚀

Astro is one of the most loved web frameworks for the past couple of years, it's a modern framework for fast content-driven websites, while also making it trivial to create dynamic web applications.

Today, we're proud to announce @clerk/astro, a new official SDK that allows developers to add authentication and authorization into their Astro application in matter of minutes.

The SDK comes fully equiped with Clerk's UI components, middleware, and low level utilities for your custom flows.

Use Clerk UI components

Clerk's pre-built UI components give you a beautiful, fully-functional user and organization management experience in minutes. Here's an example on how to use the <SignIn /> component in Astro.

src/pages/sign-in/[...signIn].astro
---
import { SignIn } from '@clerk/astro/components'
---

<SignIn path="/sign-in" />

Protect routes with Clerk Middleware

Use clerkMiddleware and the auth function to restrict logged out users from accessing the /user routes.

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

const isProtectedPage = createRouteMatcher(['/user(.*)'])

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

  return next()
})

Individual page protection

If the /me page is not protected by the middleware, you can still protect the page directly. The code below uses Astro.locals.auth() in order redirect the user the sign-in page or render their userId.

src/pages/me.astro
---
const { userId, redirectToSignIn } = Astro.locals.auth()

if (!userId) {
  return redirectToSignIn()
}
---

<p>My user id is {userId}</p>

Usage with React

Astro offers a way to use React inside your Astro application. @clerk/astro takes advantage of that and exposes components, hooks, and utilities for those cases.

src/components/Header.tsx
import { SignInButton, SignedIn, SignedOut, UserButton } from '@clerk/astro/react'

export default function Header() {
  return (
    <>
      <p>My App</p>
      <SignedOut>
        <SignInButton />
      </SignedOut>
      <SignedIn>
        <UserButton />
      </SignedIn>
    </>
  )
}

This is only a quick preview of all that @clerk/astro offers.

For more information on the available API and how to get started building Astro applications with Clerk, check out our Astro Quickstart guide.

And last but not least, we would like to acknowledge and thank all of the contributors of the previous community SDK for Astro, which was a great source of inspiration for us.