agentleFS
G1JoshiG1Joshi/Agent-Skills/skills/security/clerk/SKILL.md

clerk

Skill15 starsChanged 45 days agoMITView on GitHub

Expert Clerk authentication assistance covering Next.js middleware, React user components, webhooks, and session tokens. Use when integrating Clerk auth, protecting routes, or handling user management.

  • Reads credentials

11 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use clerk-nextjs-patterns, clerk-custom-ui and 7 more.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • elpiartheraSkill

    clerk-nextjs-patterns

    Advanced Next.js patterns - middleware, Server Actions, caching with Clerk.

    Also in 7 projects that use this

  • elpiartheraSkill

    clerk-custom-ui

    Customize Clerk component appearance - themes, layout, colors, fonts, CSS. Use for appearance styling, visual customization, branding.

    Also in 8 projects that use this

  • adrianhajdinSkill

    clerk-backend-api

    Clerk Backend REST API explorer and executor. Browse tags, inspect endpoint schemas, and execute authenticated requests. Use when listing users, managing organizations, or calling any Clerk API endpoint.

    Also in 6 projects that use this

  • sanketbodkeSkill

    clerk-billing

    Clerk Billing for subscription management - render Clerk's PricingTable

    Also in 3 projects that use this

  • nnawar706Skill

    clerk-cli

    Operate the Clerk CLI (`clerk` binary) for authentication, user/org/session management, deploy verification, instance config, env keys, and any Clerk Backend or Platform API call. Use when the user mentions Clerk management tasks, "list clerk users", "create a clerk user", "update organization", "pull clerk config", "clerk env pull", "clerk doctor", "clerk deploy", "clerk deploy status", "clerk api", or any ad-hoc Clerk API request. Prefer the CLI over raw HTTP: it handles auth, key resolution, app/instance targeting, and formatting automatically.

    Also in 4 projects that use this

  • +4 more from elpiarthera

The file

We split this skill into the rules it gives an agent

2 rules. 0 are common, 0 are distinctive, and 2 are very specific to this project.

  • 0

    Common

    Most of the 11 edited versions we read keep these.

  • 0

    Distinctive

    This author's own choices. Worth a look.

  • 2

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Verify Webhook Signatures with Svix: Always verify incoming Clerk user lifecycle webhooks using svix before updating local databases.

    line 156
  2. Very specific:

    Use Server-Side auth() in App Router: Extract userId and orgId via auth() in Server Components to eliminate client-side waterfall fetches.

    line 157

“Common” is measured: kept by at least 6 in 10 of the 11 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Clerk

Clerk is a comprehensive user management and authentication service built specifically for the modern web (React, Next.js, Remix). It focuses on providing "Drop-in" UI components (<SignIn />, <UserProfile />) rather than just APIs.

When to Use

  • Modern React & Next.js Authentication: Adding drop-in, beautifully designed authentication components to modern frontend stacks.
  • B2B SaaS Multi-Tenancy & Organizations: Managing team invites, role assignments, seat limits, and organization switching.
  • Passwordless & Passkey Auth: Enabling WebAuthn passkeys, biometric logins, and magic links out of the box.
  • Edge-Ready Middleware Verification: Validating JWT session tokens at the network edge (Cloudflare Workers, Next.js Middleware).

Quick Start

// middleware.ts
import { authMiddleware } from "@clerk/nextjs";
export default authMiddleware({});

// layout.tsx
import { ClerkProvider } from '@clerk/nextjs'
export default function RootLayout({ children }) {
  return (
    <ClerkProvider>
      <html><body>{children}</body></html>
    </ClerkProvider>
  )
}

// page.tsx (Protected)
import { UserButton, currentUser } from "@clerk/nextjs";
export default async function Page() {
  const user = await currentUser();
  if (!user) return <div>Not signed in</div>;
  return <header>Welcome {user.firstName} <UserButton /></header>;
}

Core Concepts

Drop-in Component Architecture (<SignIn />, <UserButton />)

Provides prebuilt, accessible, themed UI components that handle complete auth lifecycles:

// app/layout.tsx
import {
  ClerkProvider,
  SignInButton,
  SignedIn,
  SignedOut,
  UserButton,
} from "@clerk/nextjs";

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <ClerkProvider>
      <html lang="en">
        <body>
          <header className="flex justify-between p-4 border-b">
            <h1>Enterprise SaaS</h1>
            <SignedOut>
              <SignInButton mode="modal" />
            </SignedOut>
            <SignedIn>
              <UserButton afterSignOutUrl="/" />
            </SignedIn>
          </header>
          {children}
        </body>
      </html>
    </ClerkProvider>
  );
}

Edge Middleware Session Protection

Protects routes and extracts authenticated user claims at the edge before rendering:

// middleware.ts
import { clerkMiddleware, createRouteMatcher } from "@clerk/nextjs/server";

const isProtectedRoute = createRouteMatcher([
  "/dashboard(.*)",
  "/api/protected(.*)",
]);

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

export const config = {
  matcher: ["/((?!.*\..*|_next).*)", "/", "/(api|trpc)(.*)"],
};

Multi-Tenant Organizations & Role Checks

Manages multi-organization contexts with granular RBAC permissions:

import { auth } from "@clerk/nextjs/server";

export async function POST() {
  const { orgId, orgRole } = auth();
  if (!orgId) throw new Error("Unauthorized: Select an organization");
  if (orgRole !== "org:admin")
    throw new Error("Forbidden: Admin privileges required");

  // Execute admin organization mutations
}

Common Patterns

Next.js App Router Route Protection with Clerk Middleware

Problem: Public API endpoints inadvertently exposed without explicit session verification.

Solution: Enforce route matcher guards in Next.js middleware.ts:

import { clerkMiddleware, createRouteMatcher } from "@clerk/nextjs/server";

const isProtectedRoute = createRouteMatcher([
  "/dashboard(.*)",
  "/api/protected(.*)",
]);

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

export const config = {
  matcher: ["/((?!.*\\..*|_next).*)", "/", "/(api|trpc)(.*)"],
};

Best Practices

Do:

  • Verify Webhook Signatures with Svix: Always verify incoming Clerk user lifecycle webhooks using svix before updating local databases.
  • Use Server-Side auth() in App Router: Extract userId and orgId via auth() in Server Components to eliminate client-side waterfall fetches.
  • Theme Components with Tailored CSS: Match application design systems using Clerk's appearance prop and Tailwind utility variables.
  • Enable Passkeys by Default: Encourage users to register biometric passkeys to eliminate credential phishing risks.

Don't:

  • Expose CLERK_SECRET_KEY in frontend code: Keep secret keys strictly in server environment variables.
  • Store database IDs in client state: Treat Clerk's JWT session claims as the single source of truth for the active request.
  • Bypass route protection: Always enforce server-side protection in route handlers and middleware; do not rely on UI hiding alone.

Troubleshooting

ErrorCauseSolution
401 UnauthorizedMiddleware not configured.Ensure middleware.ts matches all routes (/((?!...))).
Hydration ErrorHTML mismatch.Wrap app in <ClerkProvider>.

References

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.