This skill provides advanced patterns for implementing authentication in Next.js applications using Clerk. Developers can learn about server vs. client authentication, middleware strategies, and user-scoped caching.
$ npx skills add https://github.com/clerk/skills --skill clerk-nextjs-patternsclerk-nextjs-patterns provides framework-specific patterns for implementing Clerk authentication in Next.js applications. The skill guides developers through server-side and client-side authentication approaches, middleware configuration, Server Actions integration, and user-scoped caching strategies. It helps teams build secure, performant authentication layers without starting from scratch. Use this skill when setting up authentication in new Next.js projects or refactoring existing auth implementations to follow Clerk best practices.
Install the skill using the command provided in the Installation section.
Implement secure authentication in Next.js applications
Protect API routes based on user authentication status
Utilize caching strategies to enhance performance of user data
$ npx skills add https://github.com/clerk/skills --skill clerk-nextjs-patternsgit clone https://github.com/clerk/skillsCopy the install command above and run it in your terminal.
Launch Claude Code, Cursor, or your preferred AI coding agent.
Use the prompt template or examples below to test the skill.
Adapt the skill to your specific use case and workflow.
Generate a Next.js authentication pattern using Clerk for [COMPANY], a [INDUSTRY] company. Focus on [SPECIFIC_FEATURE, e.g., server-side protected routes, client-side user caching, or middleware-based auth]. Include code snippets for [SERVER_COMPONENT or CLIENT_COMPONENT] and explain the trade-offs of your approach. Assume we're using Next.js 14+ and Clerk's latest SDK.
# Next.js + Clerk Authentication Pattern for Acme Corp
## Server-Side Protected API Route (Next.js 14)
```typescript
// app/api/protected/route.ts
import { auth } from '@clerk/nextjs/server';
import { NextResponse } from 'next/server';
export async function GET() {
const { userId } = auth();
if (!userId) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
// Fetch user-specific data from your DB
const userData = await db.query('SELECT * FROM users WHERE id = $1', [userId]);
return NextResponse.json({ data: userData });
}
```
## Client-Side User Caching Strategy
```typescript
// components/UserProfile.tsx
'use client';
import { useUser } from '@clerk/nextjs';
import { useEffect, useState } from 'react';
const UserProfile = () => {
const { user } = useUser();
const [cachedData, setCachedData] = useState(null);
useEffect(() => {
// Only fetch if we don't have cached data
if (user && !cachedData) {
fetch(`/api/user-cache?userId=${user.id}`)
.then(res => res.json())
.then(data => setCachedData(data));
}
}, [user, cachedData]);
return <div>{cachedData?.name || 'Loading...'}</div>;
};
```
## Middleware Configuration
```typescript
// middleware.ts
import { authMiddleware } from '@clerk/nextjs/server';
export default authMiddleware({
publicRoutes: ['/api/webhook'],
ignoredRoutes: ['/api/ignored'],
});
```
**Key Trade-offs:**
- Server-side auth provides security but increases server load
- Client-side caching improves performance but requires careful cache invalidation
- Middleware adds complexity but enables fine-grained route protectionTake a free 3-minute scan and get personalized AI skill recommendations.
Take free scan