Skill

Implement Clerk Authentication for Next.js Apps

Expert Clerk auth patterns for Next.js: middleware, server/client auth, organizations, webhooks, and API route protection.

Works with clerknextjs

72
Spark score
out of 100
Updated 25 days ago
Version 14.4.0

Add to Favorites

Why it matters

Streamline the integration of Clerk authentication into your Next.js application. This asset provides expert patterns for setting up Clerk, protecting routes with middleware, and managing user sessions effectively.

Outcomes

What it gets done

01

Configure ClerkProvider and environment variables for Next.js App Router.

02

Implement route protection using clerkMiddleware and createRouteMatcher.

03

Access authentication state in Server and Client Components using hooks and server functions.

04

Handle organizations, webhooks, and user synchronization with Clerk.

Install

Add it to your toolbox

Run in your project directory:

curl -fsSL https://spark.entire.vc/get/ag-clerk-auth | bash

Overview

Clerk Authentication

An expert-pattern skill for Clerk authentication in Next.js: middleware route protection, server/client auth, organizations, webhook user sync, API route protection, and known sharp edges. Use when adding Clerk authentication, user management, or multi-tenancy/SSO to a Next.js App Router application.

What it does

Clerk Authentication is an expert-pattern skill for implementing Clerk auth in Next.js 14/15 App Router: ClerkProvider setup, middleware route protection, Server and Client Component auth, multi-tenant Organizations, webhook-based user sync, and API route protection. Route protection is centralized in a single middleware.ts using clerkMiddleware and createRouteMatcher:

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

// Define protected route patterns
const isProtectedRoute = createRouteMatcher([
  '/dashboard(.*)',
  '/settings(.*)',
  '/api/private(.*)',
]);

// Define public routes (optional, for clarity)
const isPublicRoute = createRouteMatcher([
  '/',
  '/sign-in(.*)',
  '/sign-up(.*)',
  '/api/webhooks(.*)',
]);

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

Advanced middleware can also gate routes by organization role (auth.protect({ role: 'org:admin' })) or permission (auth.protect({ permission: 'org:premium:access' })).

When to use - and when NOT to

Use it for adding authentication, user management, or multi-tenancy/SSO to a Next.js app. Server Components read auth via auth() (userId, sessionId, orgId, claims - cheap) and currentUser() (full user object - counts toward rate limits, so reserve it for when full profile data is actually needed); Client Components use useUser(), useAuth(), useSession(), and useOrganization() hooks, always gated on isLoaded to avoid reading undefined auth state during hydration. It flags a critical sharp edge: CVE-2025-29927, a middleware-bypass vulnerability - middleware alone is not sufficient protection, every route handler must independently verify auth via auth().

Inputs and outputs

Organizations support multiple orgs per user, roles/permissions, org-scoped data queries (always filtered by orgId from auth() to prevent cross-tenant leaks), and a <Protect role="org:admin"> component for role-gated UI. Webhook sync listens for user.created/user.updated/user.deleted, verifying the payload with svix signature verification before writing to the database (using upsert rather than create to handle out-of-order event delivery), and webhook routes must be excluded from middleware protection since they come from Clerk, not authenticated users. API routes re-verify userId/orgRole from auth() in each handler rather than trusting middleware alone.

Integrations

The skill bundles ten "sharp edges" by severity (from the CVE-2025-29927 bypass and multiple-middleware-file conflicts at CRITICAL/HIGH down to webhook race conditions, async auth(), and a 4KB session-token cookie size limit that custom claims can silently exceed, at MEDIUM) and a matching set of automated validation checks - ERROR-level for exposing CLERK_SECRET_KEY client-side, hardcoded Clerk keys, un-awaited auth(), Clerk hooks used in a Server Component, and unverified webhook signatures; WARNING-level for multiple middleware files, unprotected webhook routes, and multi-tenant queries missing an orgId filter. It also defines delegation triggers to hand off adjacent needs to sibling skills: a database skill for the User table (keyed on clerkId), a payments skill for linking a Customer to the Clerk user, search/analytics/email skills for user identification and messaging.

Who it's for

Next.js developers implementing Clerk authentication who need the middleware-plus-server-verification pattern done correctly, organization-scoped multi-tenancy, and reliable webhook-driven user sync - not just the happy-path quickstart.

FAQ

Common questions

Discussion

Questions & comments · 0

Sign In Sign in to leave a comment.