Clerk

From G1Joshi/Agent-Skills · View interactive version

Clerk is an AI agent skill from the GitHub repository G1Joshi/Agent-Skills. 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.

How to use this skill

Skill file

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

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:

Don't:

Troubleshooting

| Error | Cause | Solution |

| :----------------- | :------------------------- | :-------------------------------------------------------- |

| 401 Unauthorized | Middleware not configured. | Ensure middleware.ts matches all routes (/((?!...))). |

| Hydration Error | HTML mismatch. | Wrap app in <ClerkProvider>. |

References

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.