| name | clerk-security-basics |
| description | Implement security best practices with Clerk authentication.
Use when securing your application, reviewing auth implementation,
or hardening Clerk configuration.
Trigger with phrases like "clerk security", "secure clerk",
"clerk best practices", "clerk hardening".
|
| allowed-tools | Read, Write, Edit, Grep |
| version | 1.14.0 |
| license | MIT |
| author | Jeremy Longshore <jeremy@intentsolutions.io> |
| tags | ["saas","clerk","security","authentication"] |
| compatibility | Designed for Claude Code, also compatible with Codex and OpenClaw |
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
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_live_...
CLERK_SECRET_KEY=sk_live_...
CLERK_WEBHOOK_SECRET=whsec_...
# .gitignore — ensure secrets stay out of git
.env.local
.env.*.local
.env.production
Validate at startup that secret keys are not leaked:
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
import { clerkMiddleware, createRouteMatcher } from '@clerk/nextjs/server'
import { NextResponse } from
isPublicRoute = ([
,
,
,
,
])
( (auth, req) => {
(!(req)) {
auth.()
}
response = .()
response..(, )
response..(, )
response..(, )
response..(
,
)
response
})