clerk-authentication
БесплатноБез исполняемых скриптовНе проверенGuidelines for implementing Clerk authentication in Next.js applications with middleware, hooks, and security best practices
от Mindrally★ 323 звезды на GitHubОб этом скилле
Clerk Authentication
You are an expert in Clerk authentication implementation for Next.js applications. Follow these guidelines when integrating Clerk.
Core Principles
- Implement defense-in-depth with multiple authentication layers
- Verify authentication at every data access point, not just middleware
- Protect server actions individually
- Use Clerk's built-in security features (HttpOnly cookies, CSRF protection)
Installation and Setup
npm install @clerk/nextjs
Environment Variables
# Required
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_...
CLERK_SECRET_KEY=sk_...
# Optional: Custom URLs
NEXT_PUBLIC_CLERK_SIGN_IN_URL=/sign-in
NEXT_PUBLIC_CLERK_SIGN_UP_URL=/sign-up
NEXT_PUBLIC_CLERK_AFTER_SIGN_IN_URL=/dashboard
NEXT_PUBLIC_CLERK_AFTER_SIGN_UP_URL=/dashboard
Provider Setup
App Router (app/layout.tsx)
import { ClerkProvider } from '@clerk/nextjs';
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<ClerkProvider>
<html lang="en">
<body>{children}</body>
</html>
</ClerkProvider>
);
}
With Custom Appearance
import { ClerkProvider } from '@clerk/nextjs';
import { dark } from '@clerk/themes';
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<ClerkProvider
appearance={{
baseTheme: dark,
variables: {
colorPrimary: '#3b82f6',
},
elements: {
formButtonPrimary: 'bg-blue-500 hover:bg-blue-600',
},
}}
>
<html lang="en">
<body>{children}</body>
</html>
</ClerkProvider>
);
}
Middleware Configuration
Basic Middleware (middleware.ts)
import { clerkMiddleware, createRouteMatcher } from '@clerk/nextjs/server';
// Define protected routes
const isProtectedRoute = createRouteMatcher([
'/dashboard(.*)',
'/api/protected(.*)',
'/settings(.*)',
]);
// Define public routes (optional, for clarity)
const isPublicRoute = createRouteMatcher([
'/',
'/sign-in(.*)',
'/sign-up(.*)',
'/api/public(.*)',
]);
export default clerkMiddleware(async (auth, req) => {
if (isProtectedRoute(req)) {
await auth.protect();
}
});
export const config = {
matcher: [
// Skip Next.js internals and static files
'/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)',
// Always run for API routes
'/(api|trpc)(.*)',
],
};
Advanced Middleware with Role-Based Access
import { clerkMiddleware, createRouteMatcher } from '@clerk/nextjs/server';
const isAdminRoute = createRouteMatcher(['/admin(.*)']);
const isProtectedRoute = createRouteMatcher(['/dashboard(.*)', '/api/protected(.*)']);
export default clerkMiddleware(async (auth, req) => {
const { userId, sessionClaims } = await auth();
// Admin routes require admin role
if (isAdminRoute(req)) {
if (!userId || sessionClaims?.metadata?.role !== 'admin') {
return new Response('Forbidden', { status: 403 });
}
}
// Protected routes require authentication
if (isProtectedRoute(req)) {
await auth.protect();
}
});
Authentication in Server Components
Using auth()
import { auth } from '@clerk/nextjs/server';
export default async function DashboardPage() {
const { userId } = await auth();
if (!userId) {
redirect('/sign-in');
}
// Fetch user-specific data
const data = await fetchUserData(userId);
return <Dashboard data={data} />;
}
Using currentUser()
import { currentUser } from '@clerk/nextjs/server';
export default async function ProfilePage() {
const user = await currentUser();
if (!user) {
redirect('/sign-in');
}
return (
<div>
<h1>Welcome, {user.firstName}!</h1>
<p>Email: {user.emailAddresses[0]?.emailAddress}</p>
</div>
);
}
Authentication in Client Components
useUser Hook
'use client';
import { useUser } from '@clerk/nextjs';
export function UserProfile() {
const { isLoaded, isSignedIn, user } = useUser();
if (!isLoaded) {
return <Skeleton />;
}
if (!isSignedIn) {
return <SignInPrompt />;
}
return (
<div>
<img src={user.imageUrl} alt={user.fullName ?? 'User'} />
<p>{user.fullName}</p>
</div>
);
}
useAuth Hook
'use client';
import { useAuth } from '@clerk/nextjs';
export function ProtectedAction() {
const { isLoaded, userId, getToken } = useAuth();
async function handleAction() {
if (!userId) return;
// Get a fresh token for API calls
const token = await getToken();
const response = await fetch('/api/protected', {
headers: {
Authorization: `Bearer ${token}`,
},
});
}
if (!isLoaded || !userId) {
return null;
}
return <button onClick={handleAction}>Perform Act
Установить clerk-authentication в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл clerk-authentication?
Guidelines for implementing Clerk authentication in Next.js applications with middleware, hooks, and security best practices
Как установить скилл clerk-authentication?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл clerk-authentication запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
theme-factory
Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with…
от Anthropicaccess
Manage Discord channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropicconfigure
Set up the Discord channel — save the bot token and review access policy. Use when the user pastes a Discord bot token, asks to configure Discord, asks "how…
от Anthropicaccess
Manage iMessage channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropic