Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

clerk-auth

БесплатноБез исполняемых скриптовНе проверен

Clerk is a hosted authentication and user-management service with drop-in UI components, social login, email/password, organizations, RBAC and webhooks. Use…

TerminalSkillsот TerminalSkills★ 221 звезда на GitHub

Об этом скилле

Clerk Authentication

Overview

Clerk provides hosted sign-in and sign-up, session management, user profiles, organizations (multi-tenancy) and role-based access control. Your app wraps itself in a provider, adds a middleware that attaches the session, checks it next to the data, and reads the session through auth() on the server or hooks on the client. Keys come from the Clerk dashboard (Configure, API keys). Use the pk_test_/sk_test_ keys for development and the pk_live_/sk_live_ pair only in production. Checked against @clerk/nextjs 7.9 and @clerk/express 2.1 (Clerk Core 3). Core 3 replaced <SignedIn>, <SignedOut> and <Protect> with <Show>, requires ClerkProvider inside <body>, and dropped Next.js 13 and 14.

Instructions

1. Install and configure (Next.js App Router)

Clerk's own quickstart now starts from its CLI, which detects the framework, installs the SDK, writes dev keys to .env.local and creates the middleware file (no account needed to start; it provisions a claimable dev app): npx -y clerk@latest init, then npx -y clerk@latest doctor to check the setup. Manual setup:

npm install @clerk/nextjs
# .env.local
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=   # publishable key from the Clerk dashboard (API keys)
CLERK_SECRET_KEY=                    # secret key from the same page; never commit it
NEXT_PUBLIC_CLERK_SIGN_IN_URL=/sign-in
NEXT_PUBLIC_CLERK_SIGN_UP_URL=/sign-up
// app/layout.tsx
import { ClerkProvider, Show, SignInButton, SignUpButton, UserButton } from '@clerk/nextjs';

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        <ClerkProvider afterSignOutUrl="/">
          <header>
            <Show when="signed-out"><SignInButton /><SignUpButton /></Show>
            <Show when="signed-in"><UserButton /></Show>
          </header>
          {children}
        </ClerkProvider>
      </body>
    </html>
  );
}

2. Add clerkMiddleware, then protect at the resource

On Next.js 16 the file is proxy.ts; on Next.js 15 it is middleware.ts. The code is identical. clerkMiddleware() only attaches the session to the request and protects nothing by default.

// proxy.ts (middleware.ts on Next.js 15)
import { clerkMiddleware } from '@clerk/nextjs/server';

export default clerkMiddleware();

export const config = {
  matcher: [
    '/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)',
    '/(api|trpc)(.*)',
    '/__clerk/(.*)',
  ],
};

Clerk's docs now say middleware is not the best place to protect routes: put the check in the code that reads or changes the data (pages, layouts that prefetch data, route handlers, server actions). createRouteMatcher() with auth.protect() inside clerkMiddleware still works but is deprecated, so write new code with per-resource checks.

// app/dashboard/page.tsx
import { auth } from '@clerk/nextjs/server';

export default async function Dashboard() {
  await auth.protect(); // signed out: redirect to sign-in
  return <h1>Dashboard</h1>;
}

auth.protect() on a page redirects signed-out users to sign-in. In a route handler it returns 404 for an unauthenticated request (401 inside a server action), and a signed-in user lacking the required role or permission gets 404. If you want control over the response, call auth() and check isAuthenticated yourself (next step).

3. Read the session on the server

import { auth, currentUser } from '@clerk/nextjs/server';

export default async function Page() {
  const { isAuthenticated, userId, orgId, orgRole, redirectToSignIn } = await auth();
  if (!isAuthenticated) return redirectToSignIn();

  const user = await currentUser(); // full user object (counts as a Backend API request)
  return <p>Hello {user?.firstName}</p>;
}

auth() is async in current versions: always await it. In a route handler return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) when userId is null.

4. Client hooks and components

'use client';
import { useAuth, useUser, useOrganization } from '@clerk/nextjs';

export function ProfileCard() {
  const { isSignedIn } = useAuth();
  const { user } = useUser();
  const { organization, membership } = useOrganization();
  if (!isSignedIn) return <p>Not signed in</p>;
  return <p>{user?.fullName} / {organization?.name} / {membership?.role}</p>;
}

Pre-built components from @clerk/nextjs: SignIn, SignUp, UserButton, UserProfile, OrganizationSwitcher, OrganizationList, OrganizationProfile. Mount the sign-in page at a catch-all route:

// app/sign-in/...sign-in/page.tsx
import { SignIn } from '@clerk/nextjs';
export default function SignInPage() { return <SignIn />; }

Show or hide UI with <Show when="signed-in">, <Show when="signed-out"> or `<Show when={{ permissio

Полный SKILL.md на GitHub

Установить clerk-auth в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

_scores.json

FAQ

Что делает скилл clerk-auth?

Clerk is a hosted authentication and user-management service with drop-in UI components, social login, email/password, organizations, RBAC and webhooks. Use when adding sign-in to Next.js, React, or Express apps, protecting routes with clerkMiddleware, setting up multi-tenant organizations and roles, or syncing Clerk users to your own database.

Как установить скилл clerk-auth?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл clerk-auth запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить clerk-auth с