Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Advanced Clerk auth patterns for Next.js: Server Actions, middleware, caching, and App Router integration.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
references/caching-auth.md
1# Caching with Auth23**CRITICAL**: Cache keys MUST include userId/orgId to prevent data leaking between users.45## User-Scoped Cache67```typescript8import { auth } from '@clerk/nextjs/server';9import { unstable_cache } from 'next/cache';1011export default async function ProfilePage() {12const { userId } = await auth();13if (!userId) return <div>Not signed in</div>;1415const cachedGetUserData = unstable_cache(16() => getUserData(userId),17[`user-${userId}`],18{ revalidate: 60, tags: [`user-${userId}`] }19);2021const userData = await cachedGetUserData();22return <div>{userData.name}</div>;23}24```2526## Revalidate After Updates2728```typescript29'use server';30import { revalidateTag } from 'next/cache';31import { auth } from '@clerk/nextjs/server';3233export async function updateProfile(formData: FormData) {34const { userId } = await auth();35if (!userId) throw new Error('Unauthorized');3637await db.users.update({38where: { id: userId },39data: { name: formData.get('name') as string },40});41revalidateTag(`user-${userId}`);42}43```4445## Org-Scoped Cache4647```typescript48const { orgId } = await auth();49const getOrgData = unstable_cache(50() => db.orgData.findMany({ where: { organizationId: orgId } }),51[`org-${orgId}-data`],52{ revalidate: 300, tags: [`org-${orgId}`] }53);54```5556[Docs](https://nextjs.org/docs/app/building-your-application/caching)57