clerk-astro-patterns — скилл для Claude Code: Clerk в Astro
Подсказывает агенту, как подключить Clerk к Astro: middleware, защита SSR-страниц, авторизация в API-роутах и островных компонентах.
npx skills add clerk/skills --skill clerk-astro-patterns -a claude-codeЧто делает clerk-astro-patterns
Скилл разбирает, как устроена авторизация Clerk в Astro, где режимы рендеринга расходятся. Для SSR-страниц работает Astro.locals.auth(), который наполняет middleware. Статические страницы с export const prerender = true middleware пропускает, поэтому там остаются только клиентские хуки внутри островов.
Внутри — набор справочников по задачам: настройка middleware, защита SSR-страниц, Clerk в островных компонентах, авторизация в API-роутах, связка с React. Есть таблица частых ошибок: например, Astro.locals.auth не определён, если забыть middleware в src/middleware.ts, а остров не реагирует на вход без директивы client:load.
Нужен @clerk/astro версии 4 и выше и Astro 5+. В .env кладутся PUBLIC_CLERK_PUBLISHABLE_KEY и CLERK_SECRET_KEY; в Astro клиентские переменные идут с префиксом PUBLIC_, не NEXT_PUBLIC_. Если в проекте ещё используется createRouteMatcher, это повод проверить код до обновления: в @clerk/astro 4.0 функцию убрали, проверки переносятся на страницы и API-роуты.
Какие задачи решает
- защитить SSR-страницу и перенаправить гостя на вход
- проверить пользователя внутри API-роута и вернуть 401
- подключить Clerk к островному компоненту на React
- разобраться, почему авторизация работает в dev, но не в продакшене
- перевести проект с
createRouteMatcherна проверки в страницах
Примеры запросов агенту
- Настрой clerkMiddleware в src/middleware.ts и покажи, как защитить SSR-страницу
- Добавь проверку userId в src/pages/api/data.ts и верни 401 без сессии
- Почему остров не реагирует на вход? Проверь директиву client:load
Как установить clerk-astro-patterns
1Через Skills CLI (Vercel)
npx skills add clerk/skills --skill clerk-astro-patterns -a claude-code2Вручную: положить файлы
~/.claude/skills/clerk-astro-patterns/SKILL.mdПапка скилла целиком; для одного проекта — .claude/skills/clerk-astro-patterns/
1Через Skills CLI (Vercel)
npx skills add clerk/skills --skill clerk-astro-patterns -a codex2Вручную: положить файлы
.agents/skills/clerk-astro-patterns/SKILL.mdДля всех проектов — ~/.agents/skills/
1Через Skills CLI (Vercel)
npx skills add clerk/skills --skill clerk-astro-patterns -a cursor2Вручную: положить файлы
.cursor/skills/clerk-astro-patterns/SKILL.mdCursor читает и .agents/skills/, и .claude/skills/
1GitHub CLI
gh skill install clerk/skills clerk-astro-patterns2Вручную: положить файлы
.github/skills/clerk-astro-patterns/SKILL.md1Через Skills CLI (Vercel)
npx skills add clerk/skills --skill clerk-astro-patterns -a gemini-cli2Командой платформы
gemini skills install https://github.com/clerk/skills --path skills/clerk-astro-patternsВручную: положить файлы
.devin/skills/clerk-astro-patterns/SKILL.mdСтарый путь .windsurf/skills/ тоже читается
Через Skills CLI (Vercel)
npx skills add clerk/skills --skill clerk-astro-patterns -a opencodeClaude.ai
Упакуйте папку в zip и загрузите в Settings → Capabilities → Skills
По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов
Из того же набора19
Похожие
Рядом в теме «Фронтенд и UI»
Всё по теме «Фронтенд и UI» →Вопросы о clerk-astro-patterns
Как установить clerk-astro-patterns в Claude?
Выполните npx skills add clerk/skills --skill clerk-astro-patterns -a claude-code. Скилл окажется в ~/.claude/skills/clerk-astro-patterns/SKILL.md.
Что делает clerk-astro-patterns?
Даёт агенту готовые шаблоны работы с Clerk в Astro: middleware, защита SSR-страниц, авторизация в API-роутах и хуки в островных компонентах.
Какие версии нужны для работы скилла?
@clerk/astro версии 4 и выше и Astro 5+. В @clerk/astro 4.0 удалили createRouteMatcher, поэтому старые проверки придётся перенести на страницы и API-роуты.
Исходный текст
SKILL.md · MIT
---
name: clerk-astro-patterns
description: 'Astro patterns with Clerk — middleware, SSR pages, island components,
API routes, static vs SSR rendering. Triggers on: astro clerk, clerk astro middleware,
astro protected page, clerk island component, astro API route auth, clerk astro
SSR.'
license: MIT
allowed-tools: WebFetch
metadata:
author: clerk
version: 1.0.0
---
# Astro Patterns
SDK: `@clerk/astro` v4+. Requires Astro 5+.
## What Do You Need?
| Task | Reference |
|------|-----------|
| Configure middleware (bare `clerkMiddleware()`, checks per page) | references/middleware.md |
| Protect SSR pages | references/ssr-pages.md |
| Use Clerk in island components | references/island-components.md |
| Auth in API routes | references/api-routes.md |
| Use Clerk with React in Astro | references/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
```ts
import { defineConfig } from 'astro/config'
import clerk from '@clerk/astro'
export default defineConfig({
integrations: [clerk()],
output: 'server',
})
```
### src/middleware.ts
```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](https://clerk.com/docs/reference/astro/clerk-middleware).
## SSR Page Auth
```astro
---
const { userId, orgId } = Astro.locals.auth()
if (!userId) return Astro.redirect('/sign-in')
---
<h1>Dashboard</h1>
```
## API Route Auth
```ts
// 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
| Symptom | Cause | Fix |
|---------|-------|-----|
| `Astro.locals.auth` is undefined | Missing middleware | Add `clerkMiddleware` to `src/middleware.ts` |
| Auth works in dev but not production | `output: 'static'` globally | Set `output: 'server'` or `hybrid` for protected pages |
| Static page has no auth | Prerendered pages skip middleware | Use `export const prerender = false` or move to island |
| Island not reactive to sign-in | Missing `client:load` directive | Add `client:load` to the island component |
## Import Map
| What | Import 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](https://clerk.com/docs/astro/getting-started/quickstart)
© clerk · MIT · clerk/skills