clerk-astro-patterns

por clerk

Padrões Astro com Clerk — middleware, páginas SSR, componentes ilha,

npx skills add https://github.com/clerk/skills --skill clerk-astro-patterns

Astro Patterns

SDK: @clerk/astro v4+. Requires Astro 5+.

What Do You Need?

TaskReference
Configure middleware (bare clerkMiddleware(), checks per page)references/middleware.md
Protect SSR pagesreferences/ssr-pages.md
Use Clerk in island componentsreferences/island-components.md
Auth in API routesreferences/api-routes.md
Use Clerk with React in Astroreferences/astro-react.md

Mental Model

Astro has two rendering modes per page: SSR and static prerender. Clerk works differently in each:

  • SSR pages — use Astro.locals.auth() which is populated by the middleware
  • Static pages (export const prerender = true) — Clerk middleware skips them; use client-side hooks in islands
  • Islands — React/Vue/Svelte components; use useAuth() and other hooks from @clerk/astro/react
Request → clerkMiddleware() → SSR page → Astro.locals.auth()
                                ↓
                         Island (.client) → useAuth() hook

Setup

astro.config.mjs

import { defineConfig } from 'astro/config'
import clerk from '@clerk/astro'

export default defineConfig({
  integrations: [clerk()],
  output: 'server',
})

src/middleware.ts

import { clerkMiddleware } from '@clerk/astro/server'

export const onRequest = clerkMiddleware()

The middleware populates Astro.locals.auth(). Each page and API route checks for itself. createRouteMatcher was removed in @clerk/astro 4.0 (deprecated in 3.x). Don't add it. Existing uses must move to page and API-route checks before upgrading. See the Astro clerkMiddleware() reference.

SSR Page Auth

---
const { userId, orgId } = Astro.locals.auth()
if (!userId) return Astro.redirect('/sign-in')
---

<h1>Dashboard</h1>

API Route Auth

// src/pages/api/data.ts
import type { APIRoute } from 'astro'

export const GET: APIRoute = ({ locals }) => {
  const { userId } = locals.auth()
  if (!userId) return new Response('Unauthorized', { status: 401 })

  return Response.json({ userId })
}

Common Pitfalls

SymptomCauseFix
Astro.locals.auth is undefinedMissing middlewareAdd clerkMiddleware to src/middleware.ts
Auth works in dev but not productionoutput: 'static' globallySet output: 'server' or hybrid for protected pages
Static page has no authPrerendered pages skip middlewareUse export const prerender = false or move to island
Island not reactive to sign-inMissing client:load directiveAdd client:load to the island component

Import Map

WhatImport From
clerkMiddleware, clerkClient@clerk/astro/server
useAuth, UserButton (no useUser)@clerk/astro/react
$userStore, $authStore@clerk/astro/client
Astro components (<SignIn>, etc.)@clerk/astro/components

Env Variables

# .env
PUBLIC_CLERK_PUBLISHABLE_KEY=pk_...
CLERK_SECRET_KEY=sk_...

Astro uses PUBLIC_ prefix for client-exposed variables (not NEXT_PUBLIC_).

See Also

  • clerk-setup - Initial Clerk install
  • clerk-custom-ui - Custom flows & appearance
  • clerk-orgs - B2B organizations

Docs

Astro SDK

Mais skills de clerk

clerk-testing
clerk
Utilitários de teste E2E para fluxos de autenticação do Clerk no Playwright e Cypress. Suporta ambos os frameworks Playwright e Cypress com padrões de configuração específicos (globalSetup para Playwright, comandos personalizados para Cypress). Fornece as utilidades clerkSetup() e setupClerkTestingToken() para inicializar ambientes de teste e ignorar a detecção de bots. Inclui persistência de storageState para reutilizar sessões autenticadas entre testes, reduzindo o tempo de execução. Requer chaves de API de teste ( pk_test_* ,...
clerk-swift
clerk
We need to translate the given text from English to Brazilian Portuguese. The text describes a skill called "clerk-swift" but the instruction says to not include the name unless it appears in the source text. The name "clerk-swift" does not appear in the source text, so we don't include it. The source text is: "Native Swift/iOS authentication using ClerkKit with prebuilt or custom auth flows. Supports two implementation modes: prebuilt AuthView components or fully custom native flows, selected based on project requirements Requires direct wiring of a valid Clerk publishable key in app configuration; does not use plist or environment file indirection by default Mandatory /v1/environment call after package install to determine feature availability (for example Apple Sign In support) based on..." We need to preserve product names, protocol names, URLs, numbers, technical terms. So "ClerkKit", "AuthView", "Clerk", "Apple Sign In", "/v1/environment" should remain as is. Also "plist" and "environment file" are
mosaic
clerk
Work on Mosaic UI: styling a component with slot recipes (`defineSlotRecipe` / `useRecipe` / slots / variants), or building a flow — authoring a state machine…
clerk-billing
clerk
Gerenciamento de assinaturas do Clerk Billing - renderizar a PricingTable do Clerk
clerk-nextjs-patterns
clerk
Padrões avançados de Next.js para autenticação, middleware, Server Actions e cache com escopo de usuário usando Clerk. Diferencia o await auth() no lado do servidor do hook useAuth() no lado do cliente; misturá-los é um erro comum que quebra a aplicação. Aborda estratégias de middleware (público-primeiro vs protegido-primeiro), proteção de rotas de API e códigos de status HTTP adequados (401 vs 403). Inclui padrões de cache com escopo de usuário usando unstable_cache e proteção de Server Actions contra mutações não autorizadas. Fornece compatibilidade com Core 2...
clerk-expo-patterns
clerk
Padrões Expo / React Native com Clerk — cache de tokens SecureStore, OAuth
changesets
clerk
Create or refresh a `.changeset/<slug>.md` for the current branch, or report that none is required. Triggers on "/changesets create", "add a changeset",…
clerk
clerk
O binário clerk é um gateway pré-autenticado para a Backend API e Platform API do Clerk, além de ferramentas em nível de projeto (autenticação, vinculação, pulls de env, configuração de instância). Quando o usuário perguntar algo que envolva um recurso do Clerk, use o clerk primeiro em vez de criar um curl manualmente.