clerk-nextjs-auth
БесплатноБез исполняемых скриптовНе проверенUse for Clerk in Next.js. PROACTIVELY activate for @clerk/nextjs setup, App Router auth()/currentUser(), clerkMiddleware(), proxy.ts/middleware.ts…
от JosiahSiegel★ 67 звёзд на GitHubОб этом скилле
Clerk Next.js Auth
Overview
Use this skill for Clerk integrations in Next.js projects, especially App Router projects using @clerk/nextjs. Focus on correct file placement, protected-route coverage, server/client boundaries, and modern Clerk middleware behavior.
Quick Reference
| Need | Preferred Clerk primitive |
|---|---|
| Wrap app with auth context and prebuilt components | ClerkProvider |
| Read auth state in App Router server code | auth() from @clerk/nextjs/server |
| Read current user object in App Router server code | currentUser() from @clerk/nextjs/server |
| Protect routes before rendering | clerkMiddleware() + auth.protect() |
| Group protected/public routes | createRouteMatcher() |
| Pages Router API auth | getAuth(req) |
| Administrative Backend API calls | clerkClient from server-only code |
| Client UI state | useUser(), useAuth(), useClerk() |
Setup Pattern
Install the official package and wire environment variables from the Clerk Dashboard. Clerk recommends CLI setup with npx clerk@latest init --framework next when scaffolding from scratch, but always verify the resulting files against the project's Next.js version and repo conventions.
Place ClerkProvider in the root layout for App Router apps. Keep it near the top of the React tree so prebuilt components and hooks can access Clerk context. Use client hooks only inside client components.
Use proxy.ts at the project root or src/proxy.ts for current Next.js projects. Use middleware.ts for Next.js 15 and older projects that still require middleware naming. The implementation is otherwise the same. Do not blindly create both files.
Middleware and Route Protection
Start with the rule that surprises most teams: clerkMiddleware() does not protect any route by default. Add explicit protection logic.
Use createRouteMatcher() to declare route groups. Prefer positive matchers for high-risk surfaces, such as dashboard pages and mutating APIs. Use an inverted public-route matcher only after confirming every public route is listed.
Common matcher coverage:
- Skip Next.js internals and common static files.
- Always include API/TRPC surfaces when API auth is required, such as
/(api|trpc)(.*). - Include Clerk frontend API proxy paths such as
/__clerk/(.*)when using Clerk proxying. - Include any custom Clerk proxy path.
- Include route groups that look public but call Server Actions or Route Handlers with private side effects.
Use await auth.protect() when default Clerk behavior is acceptable. Use const { isAuthenticated, redirectToSignIn } = await auth() when custom JSON responses, logging, or redirects are required.
Auth and Authorization Behavior
auth() is App Router server-only and requires clerkMiddleware(). Use it in Server Components, Route Handlers, and Server Actions. It returns the request's Auth object and redirectToSignIn().
auth.protect() can enforce:
- Signed-in access.
- Roles, permissions, and custom
has()authorization logic. - Feature and plan checks where enabled.
- Accepted token types such as
session_token,oauth_token,api_key,m2m_token, orany.
Failure behavior matters in tests:
- Authenticated and authorized returns auth state.
- Authenticated but unauthorized returns
404by default. - Unauthenticated document requests redirect to sign-in.
- Unauthenticated non-document/API requests with session token defaults can return
404. - Unauthenticated machine-token requests can return
401.
Use unauthenticatedUrl and unauthorizedUrl only when the resulting behavior is intentional for both browser navigation and API callers.
App Router Server APIs
Use auth() when only IDs, session state, active organization, token retrieval, or authorization checks are needed. Use currentUser() only when the full user object is needed because it can add Backend API work.
For token retrieval, use getToken() from the Auth object and always await it. Use a custom JWT template only when an external service requires it; otherwise prefer the default session token or server-side Clerk auth state.
In Route Handlers, call auth() or auth.protect() at the top. Authenticate and authorize before input parsing that can trigger costly work or side effects. For organization-scoped resources, compare the active organization ID to the resource's organization owner before mutating.
In Server Actions, call auth() or auth.protect() inside the action, not only in the page that renders the form. Server Actions can be invoked independently from the original UI state.
When a page needs auth-only rendering, protect at the page/layout level or in middleware. Use middleware when the app should avoid rendering work for signed-out users.
Server/Client Boundary Rules
Keep these boundaries strict:
- Use
auth(),currentUser(),clerkClient, Backend API operations, and secret keys only on the server. - Use
useUser(),useAuth(), `useSignI
Установить clerk-nextjs-auth в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл clerk-nextjs-auth?
Use for Clerk in Next.js. PROACTIVELY activate for @clerk/nextjs setup, App Router auth()/currentUser(), clerkMiddleware(), proxy.ts/middleware.ts, createRouteMatcher(), protected pages/layouts/Route Handlers/Server Actions/API routes/tRPC, auth.protect() role/permission/token checks, ClerkProvider placement, server-only clerkClient, Link prefetch, redirects, 401/404 auth failures, custom domains, __clerk proxy paths, and deployment gotchas. Provides file patterns, server/client boundary rules, matcher templates, and production checks.
Как установить скилл clerk-nextjs-auth?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл clerk-nextjs-auth запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic