SKILL.md
Clerk Security Basics
Overview
Implement security best practices for Clerk authentication: environment variable protection, middleware hardening, API route defense, webhook verification, and session security.
Prerequisites
- Clerk SDK installed and configured
- Understanding of OWASP authentication best practices
- Production deployment planned or active
Instructions
Step 1: Secure Environment Variables
# .env.local — never commit this file
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_live_... # Safe to expose (public)
CLERK_SECRET_KEY=sk_live_... # NEVER expose client-side
CLERK_WEBHOOK_SECRET=whsec_... # Server-only
# .gitignore — ensure secrets stay out of git
.env.local
.env.*.local
.env.production
Validate at startup that secret keys are not leaked:
// lib/security-check.ts
export function assertServerOnly() {
if (typeof window !== 'undefined') {
throw new Error('This module must only be used server-side')
}
if (!process.env.CLERK_SECRET_KEY) {
throw new Error('CLERK_SECRET_KEY is not configured')
}
}
Step 2: Hardened Middleware Configuration
// middleware.ts
import { clerkMiddleware, createRouteMatcher } from '@clerk/nextjs/server'
import { NextResponse } from 'next/server'
const isPublicRoute = createRouteMatcher([
'/',
'/sign-in(.*)',
'/sign-up(.*)',
'/api/webhooks(.*)',
])
export default clerkMiddleware(async (auth, req) => {
// Protect all non-public routes
if (!isPublicRoute(req)) {
await auth.protect()
}
// Add security headers
const response = NextResponse.next()
response.headers.set('X-Frame-Options', 'DENY')
response.headers.set('X-Content-Type-Options', 'nosniff')
response.headers.set('Referrer-Policy', 'strict-origin-when-cross-origin')
response.headers.set(
'Content-Security-Policy',
"frame-ancestors 'none'; form-action 'self' https://clerk.com https://*.clerk.accounts.dev"
)
return response
})
