Docs

Use Clerk with Astro and React

Astro provides an integration that enables server-side rendering and client-side hydration for your React components. This guide demonstrates how to use Clerk with Astro and React.

If you have not set up your Astro application to work with Clerk, see the quickstart guide.

terminal
npx astro add react
terminal
yarn astro add react
terminal
pnpm astro add react

Update astro.config.mjs

Add Clerk and React integrations to your Astro configuration:

astro.config.mjs
import { defineConfig } from 'astro/config'
import node from '@astrojs/node'
import react from '@astrojs/react'
import clerk from '@clerk/astro'

export default defineConfig({
  integrations: [clerk(), react()],
  output: 'server',
  adapter: node({ mode: 'standalone' }),
})

Use Clerk components

You can use the prebuilt components in your Astro pages or regular React components.

Astro pages

The following example demonstrates how to use Clerk components in Astro pages.

src/layouts/SiteLayout.astro
---
import { SignedIn, SignedOut, UserButton, SignInButton } from '@clerk/astro/react'
---

<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
    <meta name="generator" content={Astro.generator} />
  </head>
  <body>
    <header>
      <nav>
        <SignedOut client:load>
          <SignInButton client:load mode="modal" />
        </SignedOut>
        <SignedIn client:load>
          <UserButton client:load />
        </SignedIn>
      </nav>
    </header>
    <article>
      <slot />
    </article>
  </body>
</html>

React components

The following example demonstrates how to use Clerk components in React components.

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>
    </>
  )
}

Use stores in your React components

Clerk Astro provides a set of useful stores that give you access to the Clerk object, and helper methods for signing in and signing up.

The following example demonstrates how to use a Clerk Astro store.

src/components/Header.tsx
import { $userStore } from '@clerk/astro/client'

export default function Username() {
  const user = useSyncExternalStore($userStore.listen, $userStore.get, $userStore.get)
  return <>{user?.firstName}</>
}

Read user and session data

Learn how to use Clerk's hooks and helpers to access the active session and user data in your Astro application.

Client-side helpers

Learn more about Astro client-side helpers and how to use them.

Feedback

What did you think of this content?

Last updated on