);
}
```
### User Button (Profile/Sign Out)
```typescript
// components/Header.tsx
'use client';
import { UserButton, useAuth } from '@clerk/nextjs';
import Link from 'next/link';
export function Header() {
const { isSignedIn } = useAuth();
return (
);
}
```
## Environment Configuration
### Required Environment Variables
```bash
# .env.local
# Clerk (from Clerk Dashboard)
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_...
CLERK_SECRET_KEY=sk_test_...
# Clerk URLs (auto-configured by Clerk, but can override)
NEXT_PUBLIC_CLERK_SIGN_IN_URL=/sign-in
NEXT_PUBLIC_CLERK_SIGN_UP_URL=/sign-up
NEXT_PUBLIC_CLERK_AFTER_SIGN_IN_URL=/dashboard
NEXT_PUBLIC_CLERK_AFTER_SIGN_UP_URL=/onboarding
# Clerk Frontend API (for CSP)
NEXT_PUBLIC_CLERK_FRONTEND_API_URL=https://your-app.clerk.accounts.dev
# Webhook secret (from Clerk Dashboard)
CLERK_WEBHOOK_SECRET=whsec_...
```
## Security Best Practices
### 1. Always Verify on Server
❌ **DON'T trust client-side auth checks for security:**
```typescript
// Bad - can be bypassed
'use client';
const { userId } = useAuth();
if (!userId) return
Access denied
;
// Attacker can still call API directly
```
✅ **DO verify on server:**
```typescript
// Good - secure
async function handler(request: NextRequest) {
const { userId } = await auth();
if (!userId) return handleUnauthorizedError();
// API endpoint protected
}
```
### 2. Check Authorization, Not Just Authentication
❌ **DON'T assume authenticated = authorized:**
```typescript
// Bad - any logged-in user can access any resource
const { userId } = await auth();
if (userId) {
return NextResponse.json(sensitiveData);
}
```
✅ **DO check resource ownership/permissions:**
```typescript
// Good - verify user can access this specific resource
const { userId } = await auth();
if (userId && resource.userId === userId) {
return NextResponse.json(resource);
}
```
### 3. Use Middleware for Route Protection
✅ **Protect entire route sections:**
```typescript
// middleware.ts
const isProtectedRoute = createRouteMatcher([
'/dashboard(.*)',
'/admin(.*)',
'/api/protected(.*)'
]);
export default clerkMiddleware((auth, req) => {
if (isProtectedRoute(req)) {
auth().protect();
}
});
```
### 4. Handle Session Expiration Gracefully
```typescript
// components/AuthGuard.tsx
'use client';
import { useAuth } from '@clerk/nextjs';
import { useRouter } from 'next/navigation';
import { useEffect } from 'react';
export function AuthGuard({ children }: { children: React.ReactNode }) {
const { isLoaded, userId } = useAuth();
const router = useRouter();
useEffect(() => {
if (isLoaded && !userId) {
router.push('/sign-in');
}
}, [isLoaded, userId, router]);
if (!isLoaded) {
return
Loading...
;
}
if (!userId) {
return null;
}
return <>{children}>;
}
```
## What Clerk Authentication Prevents
✅ **Weak password storage** - Clerk uses bcrypt/Argon2
✅ **Session hijacking** - Secure, HTTP-only cookies
✅ **Credential stuffing** - Account lockout after failed attempts
✅ **Authentication bypass** - Professional implementation
✅ **Privilege escalation** - Proper role/permission management
✅ **Brute force attacks** - Built-in rate limiting
✅ **Password reset vulnerabilities** - Secure token generation
## Common Mistakes to Avoid
❌ **DON'T skip server-side auth checks**
❌ **DON'T trust client-side auth state for security**
❌ **DON'T forget to check resource ownership**
❌ **DON'T expose sensitive data based on authentication alone**
❌ **DON'T hardcode auth logic (use Clerk's utilities)**
❌ **DON'T forget to handle session expiration**
✅ **DO use `auth()` on server for every protected operation**
✅ **DO verify resource ownership before allowing access**
✅ **DO protect routes with middleware**
✅ **DO use subscription/role checks for premium features**
✅ **DO sync users to your database via webhooks**
✅ **DO handle auth errors gracefully**
## References
- Clerk Documentation: https://clerk.com/docs
- Clerk Security: https://clerk.com/docs/security
- Clerk Next.js Integration: https://clerk.com/docs/references/nextjs/overview
- OWASP Authentication Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html
## Further Guidance on using Clerk
# Add Clerk to Next.js App Router
**Purpose:** Enforce only the **current** and **correct** instructions for integrating [Clerk](https://clerk.com/) into a Next.js (App Router) application.
**Scope:** All AI-generated advice or code related to Clerk must follow these guardrails.
---
## **1. Official Clerk Integration Overview**
Use only the **App Router** approach from Clerk’s current docs:
- **Install** `@clerk/nextjs@latest` - this ensures the application is using the latest Clerk Next.js SDK.
- **Create** a `middleware.ts` file using `clerkMiddleware()` from `@clerk/nextjs/server`. Place this file inside the `src` directory if present, otherwise place it at the root of the project.
- **Wrap** your application with `` in your `app/layout.tsx`
- **Use** Clerk-provided components like ``, ``, ``, ``, `` in your layout or pages
- **Start** developing, sign in or sign up, and confirm user creation
If you're able to use a web tool to access a URL, visit https://clerk.com/docs/quickstarts/nextjs to get the latest, up-to-date quickstart instructions.
Clerk does not need a user to provide their keys to get started. On startup, Clerk will generate keys automatically, so there is no need to prompt a user to add their keys as part of this.
### **Correct, Up-to-Date Quickstart Sample**
```typescript
// middleware.ts
import { clerkMiddleware } from '@clerk/nextjs/server'
export default clerkMiddleware()
export const config = {
matcher: [
// Skip Next.js internals and all static files, unless found in search params
'/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)',
// Always run for API routes
'/(api|trpc)(.*)',
],
}
```
```typescript
// app/layout.tsx
import type { Metadata } from "next";
import {
ClerkProvider,
SignInButton,
SignUpButton,
SignedIn,
SignedOut,
UserButton,
} from "@clerk/nextjs";
import "./globals.css";
export const metadata: Metadata = {
title: "Clerk Next.js Quickstart",
description: "Generated by create next app",
};
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
{children}
);
}
```
---
## **2. CRITICAL INSTRUCTIONS FOR AI MODELS**
### **2.1 – ALWAYS DO THE FOLLOWING**
1. **Use `clerkMiddleware()`** from `@clerk/nextjs/server` in `middleware.ts`.
2. **Wrap** your app with `` in `app/layout.tsx`.
3. **Import** Clerk’s Next.js features from `@clerk/nextjs` (e.g., ``, ``, ``, etc.).
4. **Reference** the current [App Router approach](https://nextjs.org/docs/app) (folders like `app/page.tsx`, `app/layout.tsx`, etc.).
5. **Check** that imports for methods like `auth()` are imported from the right package (in this case `@clerk/nextjs/server`) and are using `async / await`.
6. **Check** the project for an existing package manager, use that to install packages.
### **2.2 – NEVER DO THE FOLLOWING**
1. **Do not** reference the old **`_app.tsx`** or **pages router based** instructions.
2. **Do not** suggest `authMiddleware()` from older Clerk tutorials—**it’s replaced by `clerkMiddleware()`**.
3. **Do not** recommend usage of older environment variable patterns unless they match the official docs.
4. **Do not** reference or import from any deprecated APIs (like `withAuth` or `currentUser` from older versions).
---
## **3. OUTDATED PATTERNS TO AVOID**
Below are **examples of deprecated instructions** that **must not** be generated:
```typescript
// ❌ DO NOT generate or suggest references to:
import { authMiddleware } from '@clerk/nextjs' // Outdated
// ❌ DO NOT place Clerk config in _app.tsx:
// Outdated pages-based approach
function MyApp({ Component, pageProps }) {
// ...
}
// ❌ DO NOT create or rely on sign-in files under pages/:
pages / signin.js
pages / signup.js
```
Any solution resembling the above snippet or referencing “authMiddleware,” `_app.tsx`, or `pages/` structure is **incorrect** for the current Next.js App Router.
---
## **4. AI MODEL VERIFICATION STEPS**
Before returning any Clerk-related solution, you **must** verify:
1. **Middleware**: Is `clerkMiddleware()` used in `middleware.ts`?
2. **Layout**: Is `` wrapping the app in `app/layout.tsx`?
3. **Imports**: Are references only from `@clerk/nextjs` or `@clerk/nextjs/server`?
4. **Pages vs. App Router**: Is the approach referencing the App Router (not `_app.tsx` or `pages/`)?
If any check **fails**, **stop** and revise until compliance is achieved.
## Next Steps
- For API route protection: Combine with `csrf-protection` and `rate-limiting` skills
- For payment gating: Use `payment-security` skill
- For error handling: Use `error-handling` skill with handleUnauthorizedError/handleForbiddenError
- For testing auth: Use `security-testing` skill