Index of every page on this site: llms.txt
All skills
jeremylongshore avatar

/clerk-core-workflow-b

@0d57af8
Run it yourself

Implement session management and middleware with Clerk. Use when managing user sessions, configuring route protection, or implementing token refresh and custom JWT templates. Trigger with phrases like "clerk session", "clerk middleware", "clerk route protection", "clerk token", "clerk JWT".

Use this Skill: https://skilld.dev/gh/jeremylongshore/tons-of-skills-marketplace/clerk-core-workflow-b

Nothing lands on disk. Nothing to clean up.

Fork this Skill

Edit a local copy. It keeps the author and licence.

referencesimplementation.md

≈949 tokens on demand. Your agent reads this file only when SKILL.md points to it.

Clerk Core Workflow B - Implementation Details

Clerk Middleware Configuration

// middleware.ts (project root)
import { clerkMiddleware, createRouteMatcher } from '@clerk/nextjs/server';

const isPublicRoute = createRouteMatcher([
  '/', '/sign-in(.*)', '/sign-up(.*)', '/api/webhooks(.*)', '/pricing', '/about',
]);

const isAdminRoute = createRouteMatcher(['/admin(.*)', '/api/admin(.*)']);

export default clerkMiddleware(async (auth, req) => {
  if (!isPublicRoute(req)) await auth.protect();
  if (isAdminRoute(req)) await auth.protect({ role: 'org:admin' });
});

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)(.*)',
  ],
};

API Route Protection

// app/api/protected/route.ts
import { auth } from '@clerk/nextjs/server';

export async function GET() {
  const { userId, orgId, sessionClaims } = await auth();
  if (!userId) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  return NextResponse.json({ userId, orgId, role: sessionClaims?.metadata?.role });
}

// Organization-scoped route
export async function POST(req: Request) {
  const { userId, orgId, has } = await auth();
  if (!userId) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  if (!orgId) return NextResponse.json({ error: 'Organization required' }, { status: 403 });
  if (!has({ permission: 'org:data:write' })) return NextResponse.json({ error: 'Insufficient permissions' }, { status: 403 });
  const body = await req.json();
  return NextResponse.json({ success: true });
}

Session Claims and JWT Tokens

// app/api/session/route.ts
import { auth, currentUser } from '@clerk/nextjs/server';

export async function GET() {
  const { userId, sessionId, getToken } = await auth();
  const user = await currentUser();
  if (!userId || !user) return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });

  const token = await getToken({ template: 'supabase' }); // JWT for external APIs
  return NextResponse.json({
    userId, sessionId,
    email: user.emailAddresses[0]?.emailAddress,
    fullName: `${user.firstName} ${user.lastName}`,
    publicMetadata: user.publicMetadata,
    externalToken: token ? 'present' : 'not configured',
  });
}

Server Component Auth Checks

// app/dashboard/page.tsx
import { auth } from '@clerk/nextjs/server';
import { redirect } from 'next/navigation';

export default async function DashboardPage() {
  const { userId, orgId, has } = await auth();
  if (!userId) redirect('/sign-in');

  const isAdmin = has({ role: 'org:admin' });
  const canManageBilling = has({ permission: 'org:billing:manage' });

  return (
    <div>
      <h1>Dashboard</h1>
      {isAdmin && <AdminPanel />}
      {canManageBilling && <BillingSection />}
    </div>
  );
}

// Reusable auth guard
async function AuthGuard({ children, permission }: { children: React.ReactNode; permission?: string }) {
  const { userId, has } = await auth();
  if (!userId) return null;
  if (permission && !has({ permission })) return null;
  return <>{children}</>;
}

Role-Based Navigation

// components/NavBar.tsx
import { auth } from '@clerk/nextjs/server';

export async function NavBar() {
  const { userId, has } = await auth();
  return (
    <nav>
      <a href="/">Home</a>
      {userId && <a href="/dashboard">Dashboard</a>}
      {has({ role: 'org:admin' }) && <a href="/admin">Admin</a>}
      {!userId && <a href="/sign-in">Sign In</a>}
    </nav>
  );
}

Tons of Skills by Intent Solutions | jeremylongshore.com

Source: SKILL.md on GitHub

No rule matched.

skilld matched fixed text patterns in SKILL.md and file names. Patterns miss obfuscated code.

skilld run checks every file with the same patterns. It asks for approval before it loads a Skill with a behavior marked Needs approval.

No alerts2mo3 checks · Risk SAFE
  • Gen Agent Trust Hub2mo

    The skill provides legitimate technical guidance and code templates for implementing Clerk authentication, session management, and middleware in Next.js applications. No malicious patterns or security risks were identified.

  • Socket2mo

    No alerts

  • Snyk2mo

    Risk: LOW · No issues

Signed by skilld at 0d57af8. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub yesterday.

Activeupdated 2 months ago
What it can do
Reads files Edits files
version
1.15.0
author
Jeremy Longshore <jeremy@intentsolutions.io>
tags
[
  "saas",
  "clerk",
  "clerk-core",
  "sessions",
  "middleware"
]
All 4 allowed tools
ReadWriteEditGrep
Other metadata
compatibility
Designed for Claude Code

README badge

README badge for jeremylongshore/tons-of-skills-marketplace/clerk-core-workflow-b