Token导航 LogoToken导航TokenDH.com
前端设计敏感数据github未标认证来源可访问clear审计提醒

clerk-nextjs-skillsclerk Next.js skills 前端

Agent Skill

用于辅助前端页面、组件、样式和交互逻辑的开发与维护。它适合让 Agent 生成或审查 React、Next.js、Vue、Tailwind、CSS 等相关代码,整理组件结构,或定位布局和性能问题。使用时需要结合项目现有设计系统、路由和构建方式,避免只生成孤立片段;涉及页面改动时,应配合本地预览和构建检查确认视觉效果。

总安装

6,265

周安装

251

GitHub Stars

19

下载量

2,028
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

3

许可证

MIT

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:clerk-nextjs-skills(clerk Next.js skills 前端)
来源仓库:https://github.com/gocallum/nextjs16-agent-skills
仓库路径:skills/clerk-nextjs-skills
安装命令:
npx skills add https://github.com/gocallum/nextjs16-agent-skills --skill clerk-nextjs-skills
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。不同来源提供的安装方式可能略有差异;本站展示可直接复制的安装命令,安装前请核对来源页面。

skills.shnpx skills
npx skills add https://github.com/gocallum/nextjs16-agent-skills --skill clerk-nextjs-skills

简介

clerk-nextjs-skills 辅助 Next.js 前端页面与组件的开发与维护。

  • 适用于生成或审查 React、Next.js、Tailwind CSS 相关代码。
  • 需结合项目现有设计系统和路由结构,避免生成孤立片段。
  • 涉及页面改动时应配合本地预览确认视觉效果和响应式表现。
  • 适用宿主包括 Codex、Claude、Cursor、Gemini CLI,接入前应确认版本、权限和运行环境要求。

SKILL.md

Links

Quick Start

1. Install Dependencies (Using pnpm)

pnpm add @clerk/nextjs
# For MCP server integration, also install:
pnpm add @vercel/mcp-adapter @clerk/mcp-tools

2. Create proxy.ts (Next.js 16)

The proxy.ts file replaces middleware.ts from Next.js 15. Create it at the root or in /src:

// proxy.ts (or src/proxy.ts)
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)(.*)',
  ],
}

3. Set Environment Variables

Create .env.local in your project root:

NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=your_publishable_key_here
CLERK_SECRET_KEY=your_secret_key_here
NEXT_PUBLIC_CLERK_SIGN_IN_URL=/sign-in
NEXT_PUBLIC_CLERK_SIGN_UP_URL=/sign-up
NEXT_PUBLIC_CLERK_AFTER_SIGN_IN_URL=/
NEXT_PUBLIC_CLERK_AFTER_SIGN_UP_URL=/

4. Add ClerkProvider to Layout

// app/layout.tsx
import {
  ClerkProvider,
  SignInButton,
  SignUpButton,
  SignedIn,
  SignedOut,
  UserButton,
} from '@clerk/nextjs'
import type { Metadata } from 'next'

export const metadata: Metadata = {
  title: 'My App',
}

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <ClerkProvider>
      <html lang="en">
        <body>
          <header className="flex justify-end items-center p-4 gap-4 h-16">
            <SignedOut>
              <SignInButton />
              <SignUpButton />
            </SignedOut>
            <SignedIn>
              <UserButton />
            </SignedIn>
          </header>
          {children}
        </body>
      </html>
    </ClerkProvider>
  )
}

5. Run Your App

pnpm dev

Visit http://localhost:3000 and click "Sign Up" to create your first user.

Key Concepts

proxy.ts vs middleware.ts

  • Next.js 16 (App Router): Use proxy.ts for Clerk middleware
  • Next.js ≤15: Use middleware.ts with identical code (filename only differs)
  • Clerk's clerkMiddleware() function is the same regardless of filename
  • The matcher configuration ensures proper route handling and performance

Protecting Routes

By default, clerkMiddleware() does not protect routes—all are public. Use auth.protect() to require authentication:

// Protect specific route
import { auth } from '@clerk/nextjs/server'

export default async function Page() {
  const { userId } = await auth()

  if (!userId) {
    // Redirect handled by clerkMiddleware
  }

  return <div>Protected content for {userId}</div>
}

Or protect all routes in proxy.ts:

import { clerkMiddleware } from '@clerk/nextjs/server'

export default clerkMiddleware(async (auth, req) => {
  await auth.protect()
})

Environment Variable Validation

Check for required Clerk keys before runtime:

// lib/clerk-config.ts
export function validateClerkEnv() {
  const required = [
    'NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY',
    'CLERK_SECRET_KEY',
  ]

  const missing = required.filter(key => !process.env[key])

  if (missing.length > 0) {
    throw new Error(`Missing required Clerk environment variables: ${missing.join(', ')}`)
  }
}

Accessing User Data

Use Clerk hooks in client components:

// app/components/user-profile.tsx
'use client'

import { useUser } from '@clerk/nextjs'

export function UserProfile() {
  const { user, isLoaded } = useUser()

  if (!isLoaded) return <div>Loading...</div>

  if (!user) return <div>Not signed in</div>

  return (
    <div>
      <h1>{user.fullName}</h1>
      <p>{user.primaryEmailAddress?.emailAddress}</p>
    </div>
  )
}

Or in server components/actions:

// app/actions.ts
'use server'

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

export async function getUserData() {
  const { userId } = await auth()

  if (!userId) {
    throw new Error('Unauthorized')
  }

  const clerk = await clerkClient()
  const user = await clerk.users.getUser(userId)

  return user
}

Migrating from middleware.ts (Next.js 15) to proxy.ts (Next.js 16)

Step-by-Step Migration

  1. Rename the file from middleware.ts to proxy.ts (location remains same: root or /src)
  2. Keep the code identical - No functional changes needed: // Before (middleware.ts) import {clerkMiddleware} from '@clerk/nextjs/server' export default clerkMiddleware() export const config = {...} // After (proxy.ts) - Same code import {clerkMiddleware} from '@clerk/nextjs/server' export default clerkMiddleware() export const config = {...}
  3. Update Next.js version: pnpm add next@latest
  4. Verify environment variables are still in .env.local (no changes needed)
  5. Test the migration: pnpm dev

Troubleshooting Migration

  • If routes aren't protected, ensure proxy.ts is in the correct location (root or /src)
  • Check that .env.local has all required Clerk keys
  • Clear .next cache if middleware changes don't take effect: rm -rf.next && pnpm dev
  • Verify Next.js version is 16.0+: pnpm list next

Building an MCP Server with Clerk

See CLERK_MCP_SERVER_SETUP.md for complete MCP server integration.

Quick MCP Setup Summary

  1. Install MCP dependencies: pnpm add @vercel/mcp-adapter @clerk/mcp-tools
  2. Create MCP route at app/[transport]/route.ts: import {verifyClerkToken} from '@clerk/mcp-tools/next' import {createMcpHandler, withMcpAuth} from '@vercel/mcp-adapter' import {auth, clerkClient} from '@clerk/nextjs/server' const clerk = await clerkClient() const handler = createMcpHandler((server) => {server.tool('get-clerk-user-data', 'Gets data about the Clerk user that authorized this request', {}, async (_, {authInfo}) => {const userId = authInfo!.extra!.userId! as string const userData = await clerk.users.getUser(userId) return {content: [{type: 'text', text: JSON.stringify(userData)}],}},)}) const authHandler = withMcpAuth(handler, async (_, token) => {const clerkAuth = await auth({acceptsToken: 'oauth_token'}) return verifyClerkToken(clerkAuth, token)}, {required: true, resourceMetadataPath: '/.well-known/oauth-protected-resource/mcp',},) export {authHandler as GET, authHandler as POST}
  3. Expose OAuth metadata endpoints (see references for complete setup)
  4. Update proxy.ts to exclude .well-known endpoints: import {clerkMiddleware, createRouteMatcher} from '@clerk/nextjs/server' const isPublicRoute = createRouteMatcher(['/.well-known/oauth-authorization-server(.*)', '/.well-known/oauth-protected-resource(.*)',]) export default clerkMiddleware(async (auth, req) => {if (isPublicRoute(req)) return await auth.protect()})
  5. Enable Dynamic Client Registration in Clerk Dashboard

Best Practices

1. Environment Variable Management

  • Always use .env.local for development (never commit sensitive keys)
  • Validate environment variables on application startup
  • Use NEXT_PUBLIC_ prefix ONLY for non-sensitive keys that are safe to expose
  • For production, set environment variables in your deployment platform (Vercel, etc.)

2. Route Protection Strategies

// Option A: Protect all routes
export default clerkMiddleware(async (auth, req) => {
  await auth.protect()
})

// Option B: Protect specific routes
import { createRouteMatcher } from '@clerk/nextjs/server'

const isProtectedRoute = createRouteMatcher(['/dashboard(.*)', '/api/user(.*)'])

export default clerkMiddleware(async (auth, req) => {
  if (isProtectedRoute(req)) {
    await auth.protect()
  }
})

// Option C: Public routes with opt-in protection
const isPublicRoute = createRouteMatcher(['/sign-in(.*)', '/sign-up(.*)'])

export default clerkMiddleware(async (auth, req) => {
  if (!isPublicRoute(req)) {
    await auth.protect()
  }
})

3. MCP Server Security

  • Enable Dynamic Client Registration in Clerk Dashboard
  • Keep .well-known endpoints public but protect all MCP tools with OAuth
  • Use acceptsToken: 'oauth_token' in auth() to require machine tokens
  • OAuth tokens are free during public beta (pricing TBD)
  • Always verify tokens with verifyClerkToken() before exposing user data

4. Performance & Caching

  • Use clerkClient() for server-side user queries (cached automatically)
  • Leverage React Server Components for secure user data access
  • Cache user data when possible to reduce API calls
  • Use @clerk/nextjs hooks only in Client Components ('use client')

5. Production Deployment

  • Set all environment variables in your deployment platform
  • Use Clerk's production instance keys (not development keys)
  • Test authentication flow in staging environment before production
  • Monitor Clerk Dashboard for authentication errors
  • Keep @clerk/nextjs updated: pnpm update @clerk/nextjs

Troubleshooting

Issues & Solutions

IssueSolution
"Missing environment variables"Ensure .env.local has NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY and CLERK_SECRET_KEY
Middleware not protecting routesVerify proxy.ts is in root or /src directory, not in app/
Sign-in/sign-up pages not workingCheck NEXT_PUBLIC_CLERK_SIGN_IN_URL and NEXT_PUBLIC_CLERK_SIGN_UP_URL in .env.local
User data returns nullEnsure user is authenticated: check userId is not null before calling getUser()
MCP server OAuth failsEnable Dynamic Client Registration in Clerk Dashboard OAuth Applications
Changes not taking effectClear .next cache: rm -rf.next and restart pnpm dev
"proxy.ts" not recognizedVerify Next.js version is 16.0+: pnpm list next

Common Next.js 16 Gotchas

  • File naming: Must be proxy.ts (not middleware.ts) for Next.js 16
  • Location: Place proxy.ts at project root or in /src directory, NOT in app/
  • Re-exports: Config object must be exported from proxy.ts for matcher to work
  • Async operations: clerkMiddleware() is async-ready; use await auth.protect() for route protection

Debug Mode

Enable debug logging:

// proxy.ts
import { clerkMiddleware } from '@clerk/nextjs/server'

export default clerkMiddleware((auth, req) => {
  if (process.env.DEBUG_CLERK) {
    console.log('Request URL:', req.nextUrl.pathname)
    console.log('User ID:', auth.sessionClaims?.sub)
  }
})

Run with debug:

DEBUG_CLERK=1 pnpm dev

Related Skills

Resources

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

04

需要参考平台分布和安装热度时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

补充不同宿主或平台的使用分布数据

能力 5

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Claude Code

27.99%
按下载量换算568

Antigravity

22.19%
按下载量换算450

OpenCode

16.28%
按下载量换算330

Gemini CLI

12.04%
按下载量换算244

Codex

6.52%
按下载量换算132

Cursor

3.49%
按下载量换算71

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

可疑

权限和风险

敏感数据

该 Skill 可能接触密钥、Token、环境变量或敏感配置,应进入高风险复核队列,默认不自动发布。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。来源安全扫描存在 warning/failed 结果,不能写成本站确认安全。

来源信息

继续浏览同类 Skills