Agent skill

Clerk Security Basics

by jeremylongshore in jeremylongshore/tons-of-skills-marketplace

Implement security best practices with Clerk authentication.

MITAuto-check: notesBackend & APIs

Install Clerk Security Basics

skills CLI
$ npx skills add jeremylongshore/tons-of-skills-marketplace --skill clerk-security-basics -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install jeremylongshore/tons-of-skills-marketplace clerk-security-basics --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/jeremylongshore/tons-of-skills-marketplace.git skills-src && mkdir -p .claude/skills && cp -r skills-src/skills/.curated/clerk-security-basics .claude/skills/clerk-security-basics && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
clerk-security-basics
GitHub stars
2.8k
Token cost
~1.8k tokens
SKILL.md length
217 words
Files
2 (incl. references)
Skills in repo
3,342
Repo updated
First seen
Licence
MIT

At a glance

Implement security best practices with Clerk authentication.

  • Works in 5 steps: Secure Environment Variables → Hardened Middleware Configuration → Secure API Routes → …
  • Securing your application
  • SKILL.md covers Overview, Prerequisites, Instructions and Output, plus 4 more sections
  • Reaches clerk.com; needs CLERK_SECRET_KEY and CLERK_WEBHOOK_SECRET

What it does

Clerk Security Basics is an agent skill from jeremylongshore/tons-of-skills-marketplace. 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".

Its SKILL.md is about 1.8k tokens, which your agent loads only when the skill is triggered. The skill folder holds 2 other files, including reference files (for example `references/implementation-guide.md`). Compatibility notes: Designed for Claude Code

It sits in Backend & APIs, covering Webhooks and Authentication. The repository describes itself as: Model-agnostic agent-skills platform with a harness-free canonical layer, verified adapters, and the ccpi package manager. Explore at tonsofskills.com. The licence is MIT.

When your agent uses it

  • Securing your application
  • Reviewing auth implementation
  • Hardening Clerk configuration
  • With phrases like clerk security

Example prompts

  • “clerk security”
  • “secure clerk”
  • “clerk best practices”
  • “/clerk-security-basics”

Requirements

  • A credential in NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY
  • A credential in CLERK_SECRET_KEY
  • Compatibility (from SKILL.md): Designed for Claude Code
  • Pre-approved tools (allowed-tools): Read, Write, Edit, Grep

Workflow steps

5 steps, taken from the step headings in SKILL.md.

  1. Secure Environment Variables
  2. Hardened Middleware Configuration
  3. Secure API Routes
  4. Secure Webhook Verification
  5. Session Security Best Practices

What it can do on your machine

Read from SKILL.md and the folder at commit cfae287. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves these tools, so the agent can use them without asking each time:

    • Read
    • Write
    • Edit
    • Grep

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    No scripts in the folder and no shell commands in SKILL.md (its code samples are typescript, bash and gitignore).

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    Hosts in commands or code, which the agent is likely to contact:

    • clerk.com

    Also links to:

    • cheatsheetseries.owasp.org

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names these keys or tokens, usually read from environment variables:

    • CLERK_SECRET_KEY
    • CLERK_WEBHOOK_SECRET
    • NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

  • Compatibility

    Designed for Claude Code

    From compatibility in the SKILL.md frontmatter.

Context cost

Clerk Security Basics loads about 1.8k tokens when it runs, and up to ~3.5k if it reads all its reference files. Until then it costs about 72 tokens; SKILL.md has 217 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~72
When it runs · the whole SKILL.md, loaded when a task matches
~1.8k
With references · SKILL.md plus every file in references/, read only if the agent opens them
~3.5k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check: notes

The automated check noted patterns worth knowing about, such as sudo or a known installer.

  • NoteMentions a .env fileSKILL.md:42
    # .env.local — never commit this file
  • NoteMentions a .env fileSKILL.md:50
    .env.local
  • NoteMentions a .env fileSKILL.md:51
    .env.*.local
  • NoteMentions a .env fileSKILL.md:52
    .env.production

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from jeremylongshore/tons-of-skills-marketplace at commit cfae287, republished under its MIT licence (© jeremylongshore). 217 words, ~1,838 tokens.

Download SKILL.mdSave it as .claude/skills/clerk-security-basics/SKILL.md (or your agent's skills folder). This skill also uses 1 other file; get the full folder from GitHub.
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
compatibility
Designed for Claude Code
version
1.15.0
license
MIT
author
Jeremy Longshore <jeremy@intentsolutions.io>
tags
saas, clerk, security, authentication

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
bash
# .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
# .gitignore — ensure secrets stay out of git
.env.local
.env.*.local
.env.production

Validate at startup that secret keys are not leaked:

typescript
// 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
typescript
// 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
})
Step 3: Secure API Routes
typescript
// app/api/admin/route.ts
import { auth } from '@clerk/nextjs/server'
import { NextRequest } from 'next/server'

export async function POST(req: NextRequest) {
  const { userId, has } = await auth()

  // 1. Verify authentication
  if (!userId) {
    return Response.json({ error: 'Unauthorized' }, { status: 401 })
  }

  // 2. Verify authorization (permission-based, not role-based)
  if (!has({ permission: 'org:admin:access' })) {
    return Response.json({ error: 'Forbidden' }, { status: 403 })
  }

  // 3. Validate and sanitize input
  const body = await req.json()
  if (typeof body.name !== 'string' || body.name.length > 200) {
    return Response.json({ error: 'Invalid input' }, { status: 400 })
  }

  // 4. Rate limit sensitive operations
  // (Use a rate limiter like @upstash/ratelimit)

  return Response.json({ success: true })
}
Step 4: Secure Webhook Verification
typescript
// app/api/webhooks/clerk/route.ts
import { Webhook } from 'svix'
import { headers } from 'next/headers'

export async function POST(req: Request) {
  const secret = process.env.CLERK_WEBHOOK_SECRET
  if (!secret) {
    // Log but don't expose internal state
    console.error('Missing CLERK_WEBHOOK_SECRET')
    return new Response('Internal error', { status: 500 })
  }

  const headerPayload = await headers()
  const svixHeaders = {
    'svix-id': headerPayload.get('svix-id') || '',
    'svix-timestamp': headerPayload.get('svix-timestamp') || '',
    'svix-signature': headerPayload.get('svix-signature') || '',
  }

  // Reject requests missing required headers
  if (!svixHeaders['svix-id'] || !svixHeaders['svix-signature']) {
    return new Response('Missing verification headers', { status: 400 })
  }

  const body = await req.text()
  const wh = new Webhook(secret)

  try {
    const event = wh.verify(body, svixHeaders)
    // Process verified event...
    return new Response('OK', { status: 200 })
  } catch {
    // Don't leak verification details
    return new Response('Verification failed', { status: 400 })
  }
}
Step 5: Session Security Best Practices
typescript
// Enforce session checks in sensitive operations
import { auth } from '@clerk/nextjs/server'

export async function dangerousAction() {
  const { userId, sessionId } = await auth()

  if (!userId || !sessionId) {
    throw new Error('Valid session required')
  }

  // For extra-sensitive operations, verify the session is fresh
  // by checking session claims or requiring re-authentication
  const { sessionClaims } = await auth()
  const sessionAge = Date.now() / 1000 - (sessionClaims?.iat || 0)

  if (sessionAge > 300) { // 5 minutes
    throw new Error('Session too old for this operation. Please re-authenticate.')
  }
}

Configure session settings in Clerk Dashboard:

  • Session lifetime: 7 days (default) — reduce for sensitive apps
  • Inactivity timeout: Enable for compliance requirements
  • Multi-session mode: Disable unless explicitly needed

Output

  • Environment variables secured with leak prevention
  • Middleware with security headers (CSP, X-Frame-Options, etc.)
  • API routes with auth + authz + input validation
  • Webhook endpoint with Svix signature verification
  • Session freshness checks for sensitive operations

Error Handling

ErrorCauseSolution
Secret key exposed client-sideImported in client componentMove to server-only module, add assertServerOnly()
CSP blocks Clerk UIMissing Clerk domain in CSPAdd *.clerk.accounts.dev to frame-src
Webhook verification failsClock skew on serverEnsure server time is NTP-synced
Session too old errorUser idle too longPrompt re-authentication for sensitive actions

Examples

Rate Limiting Sensitive Endpoints
typescript
import { Ratelimit } from '@upstash/ratelimit'
import { Redis } from '@upstash/redis'
import { auth } from '@clerk/nextjs/server'

const ratelimit = new Ratelimit({
  redis: Redis.fromEnv(),
  limiter: Ratelimit.slidingWindow(5, '60 s'),
})

export async function POST() {
  const { userId } = await auth()
  if (!userId) return Response.json({ error: 'Unauthorized' }, { status: 401 })

  const { success } = await ratelimit.limit(userId)
  if (!success) return Response.json({ error: 'Rate limited' }, { status: 429 })

  // Proceed with operation
}

Resources

Next Steps

Proceed to clerk-prod-checklist for production readiness review.

© jeremylongshore, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

SKILL.md and 1 other file (references) in skills/.curated/clerk-security-basics of jeremylongshore/tons-of-skills-marketplace.

  • SKILL.md
  • references/implementation-guide.md

Open the folder on GitHubat commit cfae287

Compare with similar skills

Clerk Security Basics next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Clerk Security Basics compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Clerk Security Basics this skilljeremylongshore/tons-of-skills-marketplace2.8k—~1.8kAutomated safety check: NotesMIT
API Patternsdilolabs/nosia2131 repos~2.5kAutomated safety check: PassMIT
GitHub OAuth Nango IntegrationAgentWorkforce/relay8721 repos~3.4kAutomated safety check: PassApache-2.0
Pii DetectorgoSprinto/compliance-skills133—~1.6kAutomated safety check: PassMIT
Frappe Core APIImpertio-Studio/Frappe_Claude_Skill_Package189—~3.2kAutomated safety check: PassMIT
Workosusenotra/notra260—~6.2kAutomated safety check: PassAGPL-3.0

Similar skills

  • API Patterns

    dilolabs/nosia

    Builds REST APIs using respondto blocks with Jbuilder templates following the 37signals same-controllers-different-formats philosophy.

    213 GitHub starsUsed in 1 repo~2.5k tokens
    Backend & APIsAuto-check passed
  • GitHub OAuth Nango Integration

    AgentWorkforce/relay

    A skill your agent uses when implementing GitHub OAuth + GitHub App authentication with Nango - provides two-connection pattern for user login and repo access with webhook handling

    872 GitHub starsUsed in 1 repo~3.4k tokens
    Backend & APIsAuto-check passed
  • Pii Detector

    goSprinto/compliance-skills

    Proactive PII add-on — augments the main response with PII guidance.

    133 GitHub stars~1.6k tokensUpdated 4 mo ago
    Backend & APIsAuto-check passed
  • Frappe Core API

    Impertio-Studio/Frappe_Claude_Skill_Package

    A skill your agent uses when building ERPNext/Frappe API integrations (v14/v15/v16) including REST API, RPC API, authentication, webhooks, and rate limiting.

    189 GitHub stars~3.2k tokensUpdated 24 days ago
    Backend & APIsAuto-check passed
  • Workos

    usenotra/notra

    A skill your agent uses when the user asks for a WorkOS docs URL, term, or dashboard field (Sign-in endpoint, initiateloginuri, Redirect URI, WORKOS env vars), or is implementing, debugging, or…

    260 GitHub stars~6.2k tokensUpdated today
    Backend & APIsAuto-check passed
  • Clerk Auth

    davila7/claude-code-templates

    Expert patterns for Clerk auth implementation, middleware, organizations, webhooks, and user sync Use when: adding authentication, clerk auth, user authentication, sign in, sign up.

    33k GitHub starsUsed in 5 repos~376 tokens
    Backend & APIsAuto-check passed

More from jeremylongshore/tons-of-skills-marketplace

All 3,342 skills in this repo
  • Performing Security Code Review

    jeremylongshore/tons-of-skills-marketplace

    Execute this skill enables AI assistant to conduct a security-focused code review using the security-agent plugin.

    2.8k GitHub starsUsed in 2 repos~1.3k tokens
    Auto-check: notes
  • Adapting Transfer Learning Models

    jeremylongshore/tons-of-skills-marketplace

    Build this skill automates the adaptation of pre-trained machine learning models using transfer learning techniques.

    2.8k GitHub stars~1.1k tokensUpdated today
    Auto-check passed
  • Agent Context Loader

    jeremylongshore/tons-of-skills-marketplace

    Execute proactive auto-loading: automatically detects and loads agents.md files.

    2.8k GitHub stars~1.1k tokensUpdated today
    Auto-check passed
  • Aggregating Performance Metrics

    jeremylongshore/tons-of-skills-marketplace

    Aggregate and centralize performance metrics from applications, systems, databases, caches, and services.

    2.8k GitHub stars~1.2k tokensUpdated today
    Auto-check passed
  • Analyzing Capacity Planning

    jeremylongshore/tons-of-skills-marketplace

    Execute this skill enables AI assistant to analyze capacity requirements and plan for future growth.

    2.8k GitHub stars~947 tokensUpdated today
    Auto-check passed
  • Analyzing Database Indexes

    jeremylongshore/tons-of-skills-marketplace

    Process use when you need to work with database indexing. An agent skill from jeremylongshore/tons-of-skills-marketplace.

    2.8k GitHub stars~2k tokensUpdated today
    Auto-check passed

Categories

Questions about Clerk Security Basics

What does Clerk Security Basics do?

Implement security best practices with Clerk authentication. Clerk Security Basics is an agent skill from jeremylongshore/tons-of-skills-marketplace. Implement security best practices with Clerk authentication.

When should I use Clerk Security Basics?

Clerk Security Basics fits situations like: securing your application; reviewing auth implementation; hardening Clerk configuration; with phrases like clerk security.

How do I install Clerk Security Basics in Claude Code?

Run `npx skills add jeremylongshore/tons-of-skills-marketplace --skill clerk-security-basics -a claude-code`. Or copy the skill folder (skills/.curated/clerk-security-basics in jeremylongshore/tons-of-skills-marketplace) into .claude/skills/clerk-security-basics in your project. Claude Code loads it when a task matches its description.

How do I install Clerk Security Basics in Codex?

Run `npx skills add jeremylongshore/tons-of-skills-marketplace --skill clerk-security-basics -a codex`. Or copy the skill folder (skills/.curated/clerk-security-basics in jeremylongshore/tons-of-skills-marketplace) into .agents/skills/clerk-security-basics in your project. Codex loads it when a task matches its description.

Can I use Clerk Security Basics in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add jeremylongshore/tons-of-skills-marketplace --skill clerk-security-basics -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/clerk-security-basics, .gemini/skills/clerk-security-basics, .github/skills/clerk-security-basics and .opencode/skills/clerk-security-basics in your project.

What does Clerk Security Basics need to run?

Going by SKILL.md and its folder, Clerk Security Basics needs credentials named CLERK_SECRET_KEY, CLERK_WEBHOOK_SECRET and NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY. Our summary lists: A credential in NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY; A credential in CLERK_SECRET_KEY. Its frontmatter pre-approves these tools: Read, Write, Edit, Grep. Compatibility (from SKILL.md): Designed for Claude Code.

Does Clerk Security Basics access the network?

SKILL.md names 2 domains. In commands or code: clerk.com; the agent is likely to contact it when it follows the instructions. As links in the text: cheatsheetseries.owasp.org. This is read from the text; nothing was executed.

Is Clerk Security Basics safe to install?

Our automated static check of SKILL.md found notes only (mentions a .env file), nothing it rates as a warning. It is not a guarantee. Review the folder before installing.

What licence does Clerk Security Basics use?

Clerk Security Basics is published under the MIT licence (declared in SKILL.md). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Clerk Security Basics use?

About 1.8k tokens (SKILL.md is roughly 7.4k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full. Its references folder adds about 1.7k tokens, read only when the agent opens those files.

What are the alternatives to Clerk Security Basics?

Skills that share tags, products or a category with Clerk Security Basics: API Patterns (dilolabs/nosia, 213 stars), GitHub OAuth Nango Integration (AgentWorkforce/relay, 872 stars), Pii Detector (goSprinto/compliance-skills, 133 stars) and Frappe Core API (Impertio-Studio/Frappe_Claude_Skill_Package, 189 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Clerk Security Basics?

jeremylongshore (a GitHub user) maintains it in jeremylongshore/tons-of-skills-marketplace, which has 2,827 GitHub stars. The repository holds 3,342 skills in this directory. The repository was last updated on October 10, 2026.

Source: jeremylongshore/tons-of-skills-marketplace on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.