All skills
clerk avatar

/clerk-nextjs-patterns

@247b8b9 official
by clerkclerk/skills83 stars
5

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

Use this Skill: https://skilld.dev/gh/clerk/skills/clerk-nextjs-patterns

This session only. Nothing lands on disk.

referencescaching-auth.md

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

Caching with Auth

CRITICAL: Cache keys MUST include userId/orgId to prevent data leaking between users.

User-Scoped Cache

import { auth } from '@clerk/nextjs/server';
import { unstable_cache } from 'next/cache';

export default async function ProfilePage() {
  const { userId } = await auth();
  if (!userId) return <div>Not signed in</div>;

  const cachedGetUserData = unstable_cache(
    () => getUserData(userId),
    [`user-${userId}`],
    { revalidate: 60, tags: [`user-${userId}`] }
  );

  const userData = await cachedGetUserData();
  return <div>{userData.name}</div>;
}

Revalidate After Updates

'use server';
import { revalidateTag } from 'next/cache';
import { auth } from '@clerk/nextjs/server';

export async function updateProfile(formData: FormData) {
  const { userId } = await auth();
  if (!userId) throw new Error('Unauthorized');

  await db.users.update({
    where: { id: userId },
    data: { name: formData.get('name') as string },
  });
  revalidateTag(`user-${userId}`);
}

Org-Scoped Cache

const { orgId } = await auth();
const getOrgData = unstable_cache(
  () => db.orgData.findMany({ where: { organizationId: orgId } }),
  [`org-${orgId}-data`],
  { revalidate: 300, tags: [`org-${orgId}`] }
);

Docs

Source: SKILL.md on GitHub

No alerts16d5 checks · Risk SAFE
  • Gen Agent Trust Hub16d

    This skill provides secure and standardized patterns for implementing authentication and authorization in Next.js applications using Clerk. It includes best practices for middleware, server actions, and caching.

  • Socket16d

    No alerts

  • Snyk16d

    Risk: LOW · No issues

  • Runlayer6mo

    7 files scanned · No issues

  • ZeroLeaks5mo

    Score: 93/100 · 2 sections analyzed

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

Last checked against GitHub yesterday.

Activeupdated 5 months ago
What it can do
Network
metadata
{
  "author": "clerk",
  "version": "2.2.0"
}
All 1 allowed tools
WebFetch
Other metadata
compatibility
Requires NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY and CLERK_SECRET_KEY. For manual JWT verification (standalone API servers without Clerk middleware), additionally requires CLERK_JWT_KEY or CLERK_PEM_PUBLIC_KEY.

README badge

README badge for clerk/skills/clerk-nextjs-patterns

Provides Next.js patterns for Clerk auth using Server Components, Server Actions, middleware, and caching. Covers server vs client auth APIs (`auth()` vs hooks), protecting mutations, session tokens for external APIs, and manual JWT verification for standalone servers.

Generated from the current SKILL.md.

Does this skill require Clerk to be already set up in my Next.js project?
Yes. See the `clerk-setup` skill for initial installation. This skill covers advanced patterns — middleware, Server Actions, caching, and auth flows — assuming Clerk is already configured with NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY and CLERK_SECRET_KEY.
What's the difference between `auth()` and `useAuth()`?
`auth()` is a server-side async function for Server Components and Route Handlers. `useAuth()` is a client-side hook for Client Components. Never mix them — use the appropriate API for your component type.
How do I protect Server Actions from unauthorized calls?
Call `await auth()` at the start of your Server Action and check `isAuthenticated` or `userId`. If the user fails the check, throw an error or return early. The skill includes a reference guide in `references/server-actions.md`.
Does this work with Core 2 Clerk SDK?
Yes, but with differences. The skill notes Core 2 limitations inline — for example, `isAuthenticated` and `sessionStatus` don't exist in Core 2, so use `!!userId` instead. Check your `package.json` for the installed version.
Can I use this for standalone API servers without Clerk middleware?
Yes. The skill covers manual JWT verification using `@clerk/backend`'s `verifyToken` or the `jsonwebtoken` library. You'll need CLERK_JWT_KEY or CLERK_PEM_PUBLIC_KEY in addition to the standard Clerk environment variables.

Generated from the current SKILL.md. These answers refresh after source changes.