CommunityProgramación y desarrollogithub.com

clerk/clerk-astro-patterns

Patrones de Astro con Clerk — middleware, páginas SSR, componentes isla, rutas API, renderizado estático vs SSR. Se activa con: astro clerk, clerk astro middleware, astro protected page, clerk island component, astro API route auth, clerk astro SSR.

¿Qué es clerk-astro-patterns?

Este skill proporciona una guía completa para integrar Clerk, una plataforma de autenticación y gestión de usuarios, con Astro, un framework moderno para construir sitios web rápidos. Está diseñado para desarrolladores que necesitan implementar autenticación en aplicaciones Astro que utilizan middleware, páginas renderizadas del lado del servidor (SSR), componentes isla interactivos, y rutas API. El skill explica cómo configurar middleware de Clerk para proteger rutas, cómo manejar la autenticación en páginas SSR y estáticas, cómo crear componentes isla que gestionan sesiones de usuario, y cómo autenticar peticiones en rutas API. Es útil porque Centraliza y simplifica la integración de Clerk en proyectos Astro, ofreciendo patrones claros y probados. Soporta las plataformas Clerk y Astro, y se activa naturalmente cuando el usuario menciona términos como 'astro clerk', 'clerk astro middleware' o 'astro API route auth'. El skill funciona analizando las consultas del usuario para detectar estos patrones y proporcionar ejemplos de código y configuraciones específicas.

Compatible con~Claude Code~Codex CLI~Cursor
Part ofReact
npx skills add https://github.com/clerk/skills/tree/main/skills/clerk-astro-patterns

Installed? Explore more Programación y desarrollo skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

Preguntar en tu IA favorita

Abre un nuevo chat con esta habilidad de agente ya precargada.

Documentación

¿Qué hace clerk-astro-patterns?

Patrones de Astro con Clerk — middleware, páginas SSR, componentes isla, rutas API, renderizado estático vs SSR. Se activa con: astro clerk, clerk astro middleware, astro protected page, clerk island component, astro API route auth, clerk astro SSR.

Requisitos previos

  • Tener un proyecto Astro configurado.
  • Tener una cuenta en Clerk y un proyecto creado.
  • Instalar los paquetes necesarios:
npm install @clerk/clerk-astro

Configuración del middleware

Crea un archivo src/middleware.ts para proteger rutas y manejar la autenticación:

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

export const onRequest = clerkMiddleware((auth, request) => {
  // Lógica personalizada opcional
});

Define las rutas públicas en tu archivo de configuración (opcional):

// astro.config.mjs
export default defineConfig({
  output: 'server',
  // ...
});

Páginas SSR con Clerk

Para páginas renderizadas del lado del servidor, utiliza el hook Auth:

---
import { Auth } from '@clerk/clerk-astro';
---

<Auth>
  {({ user }) => (
    <div>
      <h1>Bienvenido, {user?.firstName}!</h1>
    </div>
  )}
</Auth>

Componentes isla

Crea un componente isla para manejar la interfaz de autenticación:

---
// src/components/SignIn.astro
import { ClerkProvider } from '@clerk/clerk-astro';
---

<ClerkProvider>
  <SignIn />
</ClerkProvider>

Luego, úsalo en cualquier página:

---
import SignIn from '../components/SignIn.astro';
---

<SignIn client:load />

Rutas API

Para autenticar rutas API, usa getAuth desde @clerk/clerk-astro/server:

// src/pages/api/protected.ts
export async function GET(request: Request) {
  const { userId } = getAuth(request);
  if (!userId) {
    return new Response('No autorizado', { status: 401 });
  }
  // Lógica protegida
  return new Response(JSON.stringify({ userId }), { status: 200 });
}

Renderizado estático vs SSR

Para páginas estáticas, usa Clerk en tiempo de construcción, pero ten en cuenta que la autenticación solo se verificará en el cliente. Para SSR, habilita output: 'server' en la configuración de Astro y usa el middleware.

Referencias


Este skill se activa automáticamente con los triggers mencionados y proporciona ejemplos prácticos para cada patrón.

Individual skills in this repo

This repo contains 19 individual skills — each has its own dedicated page.

clerk/clerk

Clerk authentication router. Use when user asks about adding authentication, setting up Clerk, custom sign-in flows, Swift or native iOS auth, native Android auth, Next.js patterns, React patterns, Vue patterns, Nuxt patterns, Astro patterns, TanStack Start patterns, Expo patterns, React Router patterns, Chrome Extension patterns, organizations, billing, subscriptions, payments, pricing, plans, seat-based pricing, feature entitlements, syncing users, or testing. Automatically routes to the specific skill based on their task.

clerk/clerk-android

Implement Clerk authentication for native Android apps using Kotlin and Jetpack Compose with clerk-android source-guided patterns. Use for prebuilt AuthView/UserButton or custom API-driven auth flows. Do not use for Expo or React Native projects.

clerk/clerk-backend-api

Clerk Backend REST API explorer and executor. Browse tags, inspect endpoint schemas, and execute authenticated requests. Use when listing users, managing organizations, or calling any Clerk API endpoint.

clerk/clerk-billing

Clerk Billing for subscription management - render Clerk's PricingTable and in-app checkout drawer, configure subscription plans, seat-limit plans for B2B, feature entitlements with has(), and billing webhooks. Use for SaaS monetization, plan gating, checkout flows, trials, invoicing, and subscription lifecycle management.

clerk/clerk-chrome-extension-patterns

Chrome Extension auth with @clerk/chrome-extension -- popup/sidepanel setup, syncHost for OAuth/SAML via web app, createClerkClient for service workers and headless extensions, stable CRX ID. Triggers on: Chrome extension auth, Plasmo clerk, popup sign-in, syncHost, background service worker token, createClerkClient, headless extension.

clerk/clerk-custom-ui

Custom authentication flows and component appearance - hooks (useSignIn, useSignUp), themes, colors, fonts, CSS. Use for custom sign-in/sign-up flows, appearance styling, visual customization, branding.

clerk/clerk-expo

Implement Clerk authentication for Expo and React Native apps using @clerk/expo source-guided patterns. Use for prebuilt AuthView/UserButton or custom hook-driven auth flows. Do not use for native iOS/Swift, native Android/Kotlin, or web framework projects.

clerk/clerk-expo-patterns

Expo / React Native patterns with Clerk — SecureStore token cache, OAuth deep linking, useAuth in native, Expo Router protected routes, push notifications with user context. Triggers on: expo clerk, clerk react native, SecureStore token cache, expo router auth, OAuth deep link clerk, mobile auth clerk.

clerk/clerk-nextjs-patterns

Advanced Next.js patterns - middleware, Server Actions, caching with Clerk.

clerk/clerk-nuxt-patterns

Nuxt 3 auth patterns with @clerk/nuxt - middleware, composables, server API routes, SSR. Triggers on: Nuxt auth, useAuth composable, clerkMiddleware Nuxt, server API Clerk, Nuxt route protection.

clerk/clerk-orgs

Clerk Organizations for B2B SaaS - create multi-tenant apps with org switching, role-based access, verified domains, and enterprise SSO. Use for team workspaces, RBAC, org-based routing, member management.

clerk/clerk-react-patterns

React SPA auth patterns with @clerk/react for Vite/CRA - ClerkProvider setup, useAuth/useUser/useClerk hooks, React Router protected routes, custom sign-in flows. Triggers on: Vite Clerk setup, React Router auth, useAuth hook, protected route, custom sign-in form React.

clerk/clerk-react-router-patterns

React Router v7 patterns with Clerk — rootAuthLoader, getAuth in loaders, clerkMiddleware, protected routes, SSR user data, org switching. Triggers on: react-router auth, rootAuthLoader, getAuth loader, react-router protected route, loader authentication, SSR auth react-router.

clerk/clerk-setup

Add Clerk authentication to any project by following the official quickstart guides.

clerk/clerk-swift

Implement Clerk authentication for native Swift and iOS apps using ClerkKit and ClerkKitUI source-guided patterns. Use for prebuilt AuthView or custom native flows. Do not use for Expo or React Native projects.

clerk/clerk-tanstack-patterns

TanStack React Start auth patterns with @clerk/tanstack-react-start - createServerFn, beforeLoad guards, loaders, Vinxi server. Triggers on: TanStack auth, createServerFn clerk, beforeLoad protection, TanStack Start middleware.

clerk/clerk-testing

E2E testing for Clerk apps. Use with Playwright or Cypress for auth flow tests.

clerk/clerk-vue-patterns

Vue 3 patterns with Clerk — composables (useAuth, useUser, useClerk, useOrganization), Vue Router guards, Pinia auth store integration. Triggers on: vue clerk, useAuth vue, clerk composables, vue router clerk guard, pinia auth clerk. For Nuxt, use clerk-nuxt-patterns instead.

clerk/clerk-webhooks

Clerk webhooks for real-time events and data syncing. Verify with verifyWebhook from the framework-specific package. Handle user, session, organization, billing, and payment events. Build event-driven features like database sync, notifications, and integrations.

Skills relacionados