clerk-debug-bundle

0
1
Source

Collect comprehensive debug information for Clerk issues. Use when troubleshooting complex problems, preparing support tickets, or diagnosing intermittent issues. Trigger with phrases like "clerk debug", "clerk diagnostics", "clerk support ticket", "clerk troubleshooting".

Install

mkdir -p .claude/skills/clerk-debug-bundle && curl -L -o skill.zip "https://mcp.directory/api/skills/download/4759" && unzip -o skill.zip -d .claude/skills/clerk-debug-bundle && rm skill.zip

Installs to .claude/skills/clerk-debug-bundle

About this skill

Clerk Debug Bundle

Current State

!node --version 2>/dev/null || echo 'N/A' !npm list @clerk/nextjs @clerk/clerk-react @clerk/express 2>/dev/null | grep clerk || echo 'No Clerk packages found'

Overview

Collect all necessary debug information for Clerk troubleshooting and support tickets. Generates an environment report, runtime health check, client-side debug panel, and support bundle.

Prerequisites

  • Clerk SDK installed
  • Access to application logs
  • Browser with developer tools

Instructions

Step 1: Environment Debug Script

// scripts/clerk-debug.ts
import { createClerkClient } from '@clerk/backend'

async function collectDebugInfo() {
  const info: Record<string, any> = {
    timestamp: new Date().toISOString(),
    nodeVersion: process.version,
    platform: process.platform,
    env: {
      hasPK: !!process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY,
      hasSK: !!process.env.CLERK_SECRET_KEY,
      pkPrefix: process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY?.slice(0, 8) + '...',
      nodeEnv: process.env.NODE_ENV,
    },
  }

  // Test API connectivity
  try {
    const clerk = createClerkClient({ secretKey: process.env.CLERK_SECRET_KEY! })
    const users = await clerk.users.getUserList({ limit: 1 })
    info.apiConnectivity = { status: 'ok', userCount: users.totalCount }
  } catch (err: any) {
    info.apiConnectivity = { status: 'error', message: err.message, code: err.status }
  }

  // Check package versions
  try {
    const pkg = require('./package.json')
    info.packages = Object.entries(pkg.dependencies || {})
      .filter(([k]) => k.includes('clerk'))
      .reduce((acc, [k, v]) => ({ ...acc, [k]: v }), {})
  } catch {
    info.packages = 'Could not read package.json'
  }

  console.log(JSON.stringify(info, null, 2))
  return info
}

collectDebugInfo()

Run with:

npx tsx scripts/clerk-debug.ts

Step 2: Runtime Health Check Endpoint

// app/api/clerk-health/route.ts
import { auth, clerkClient } from '@clerk/nextjs/server'

export async function GET() {
  const checks: Record<string, { status: string; detail?: string }> = {}

  // Check 1: SDK loaded
  checks.sdk = { status: 'ok', detail: 'Clerk SDK loaded' }

  // Check 2: Auth function works
  try {
    const { userId } = await auth()
    checks.auth = { status: 'ok', detail: userId ? `Authenticated as ${userId}` : 'Not authenticated (expected for health check)' }
  } catch (err: any) {
    checks.auth = { status: 'error', detail: err.message }
  }

  // Check 3: Backend API connectivity
  try {
    const client = await clerkClient()
    await client.users.getUserList({ limit: 1 })
    checks.backendApi = { status: 'ok', detail: 'API reachable' }
  } catch (err: any) {
    checks.backendApi = { status: 'error', detail: err.message }
  }

  // Check 4: Environment variables
  checks.envVars = {
    status: process.env.CLERK_SECRET_KEY ? 'ok' : 'error',
    detail: process.env.CLERK_SECRET_KEY ? 'Secret key configured' : 'CLERK_SECRET_KEY missing',
  }

  const allOk = Object.values(checks).every((c) => c.status === 'ok')
  return Response.json({ healthy: allOk, checks }, { status: allOk ? 200 : 503 })
}

Step 3: Client-Side Debug Component

'use client'
import { useAuth, useUser, useSession } from '@clerk/nextjs'
import { useState } from 'react'

export function ClerkDebugPanel() {
  const { userId, isLoaded: authLoaded, getToken } = useAuth()
  const { user, isLoaded: userLoaded } = useUser()
  const { session } = useSession()
  const [tokenPreview, setTokenPreview] = useState<string | null>(null)

  if (process.env.NODE_ENV === 'production') return null // Hide in prod

  const inspectToken = async () => {
    const token = await getToken()
    if (token) {
      const payload = JSON.parse(atob(token.split('.')[1]))
      setTokenPreview(JSON.stringify(payload, null, 2))
    }
  }

  return (
    <details style={{ position: 'fixed', bottom: 10, right: 10, background: '#1a1a2e', color: '#eee', padding: 12, borderRadius: 8, fontSize: 12, zIndex: 9999 }}>
      <summary>Clerk Debug</summary>
      <pre>
        Auth loaded: {String(authLoaded)}{'\n'}
        User loaded: {String(userLoaded)}{'\n'}
        User ID: {userId || 'null'}{'\n'}
        Email: {user?.primaryEmailAddress?.emailAddress || 'N/A'}{'\n'}
        Session ID: {session?.id || 'null'}{'\n'}
        Session status: {session?.status || 'N/A'}{'\n'}
        Last active: {session?.lastActiveAt ? new Date(session.lastActiveAt).toISOString() : 'N/A'}
      </pre>
      <button onClick={inspectToken}>Inspect JWT</button>
      {tokenPreview && <pre>{tokenPreview}</pre>}
    </details>
  )
}

Step 4: Request Debug Middleware

// middleware.ts — add debug logging (development only)
import { clerkMiddleware } from '@clerk/nextjs/server'

export default clerkMiddleware(async (auth, req) => {
  if (process.env.CLERK_DEBUG === 'true') {
    const { userId, sessionId } = await auth()
    console.log(`[Clerk Debug] ${req.method} ${req.nextUrl.pathname}`, {
      userId: userId || 'anonymous',
      sessionId: sessionId?.slice(0, 8) || 'none',
      cookies: req.cookies.getAll().map((c) => c.name).filter((n) => n.startsWith('__clerk')),
    })
  }
})

Step 5: Generate Support Bundle

#!/bin/bash
# scripts/clerk-support-bundle.sh
set -euo pipefail

BUNDLE_DIR="clerk-debug-$(date +%Y%m%d-%H%M%S)"
mkdir -p "$BUNDLE_DIR"

# Package versions
npm list --depth=0 2>/dev/null | grep clerk > "$BUNDLE_DIR/packages.txt" || true

# Environment check (redacted)
echo "NODE_ENV: ${NODE_ENV:-not set}" > "$BUNDLE_DIR/env.txt"
echo "Has PK: $([ -n "${NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY:-}" ] && echo yes || echo no)" >> "$BUNDLE_DIR/env.txt"
echo "Has SK: $([ -n "${CLERK_SECRET_KEY:-}" ] && echo yes || echo no)" >> "$BUNDLE_DIR/env.txt"
echo "PK prefix: ${NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY:0:8}..." >> "$BUNDLE_DIR/env.txt"

# Middleware check
[ -f middleware.ts ] && cp middleware.ts "$BUNDLE_DIR/" || echo "No middleware.ts found" > "$BUNDLE_DIR/middleware-missing.txt"

# Health check
curl -s http://localhost:3000/api/clerk-health > "$BUNDLE_DIR/health.json" 2>/dev/null || echo '{"error":"app not running"}' > "$BUNDLE_DIR/health.json"

# Bundle it
tar czf "${BUNDLE_DIR}.tar.gz" "$BUNDLE_DIR"
rm -rf "$BUNDLE_DIR"
echo "Support bundle: ${BUNDLE_DIR}.tar.gz"

Output

  • Environment debug script showing SDK versions and API connectivity
  • /api/clerk-health endpoint for runtime health checks
  • Client-side debug panel (dev-only) showing auth state and JWT contents
  • Request logging middleware with Clerk cookie inspection
  • Support bundle script for filing Clerk support tickets

Error Handling

IssueDebug Action
Auth not workingHit /api/clerk-health, check backendApi status
Token issuesUse debug panel "Inspect JWT" to view claims and expiry
Middleware not runningEnable CLERK_DEBUG=true, check console for request logs
Session not persistingCheck debug panel for __clerk cookies, verify domain

Examples

Quick One-Liner Debug Check

# Verify Clerk API connectivity from CLI
curl -s -H "Authorization: Bearer $CLERK_SECRET_KEY" \
  https://api.clerk.com/v1/users?limit=1 | jq '.total_count'

Resources

Next Steps

Proceed to clerk-rate-limits for understanding Clerk rate limits.

svg-icon-generator

jeremylongshore

Svg Icon Generator - Auto-activating skill for Visual Content. Triggers on: svg icon generator, svg icon generator Part of the Visual Content skill category.

11340

d2-diagram-creator

jeremylongshore

D2 Diagram Creator - Auto-activating skill for Visual Content. Triggers on: d2 diagram creator, d2 diagram creator Part of the Visual Content skill category.

9033

automating-mobile-app-testing

jeremylongshore

This skill enables automated testing of mobile applications on iOS and Android platforms using frameworks like Appium, Detox, XCUITest, and Espresso. It generates end-to-end tests, sets up page object models, and handles platform-specific elements. Use this skill when the user requests mobile app testing, test automation for iOS or Android, or needs assistance with setting up device farms and simulators. The skill is triggered by terms like "mobile testing", "appium", "detox", "xcuitest", "espresso", "android test", "ios test".

18828

performing-penetration-testing

jeremylongshore

This skill enables automated penetration testing of web applications. It uses the penetration-tester plugin to identify vulnerabilities, including OWASP Top 10 threats, and suggests exploitation techniques. Use this skill when the user requests a "penetration test", "pentest", "vulnerability assessment", or asks to "exploit" a web application. It provides comprehensive reporting on identified security flaws.

5519

designing-database-schemas

jeremylongshore

Design and visualize efficient database schemas, normalize data, map relationships, and generate ERD diagrams and SQL statements.

12516

optimizing-sql-queries

jeremylongshore

This skill analyzes and optimizes SQL queries for improved performance. It identifies potential bottlenecks, suggests optimal indexes, and proposes query rewrites. Use this when the user mentions "optimize SQL query", "improve SQL performance", "SQL query optimization", "slow SQL query", or asks for help with "SQL indexing". The skill helps enhance database efficiency by analyzing query structure, recommending indexes, and reviewing execution plans.

5513

You might also like

flutter-development

aj-geddes

Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.

1,6851,430

ui-ux-pro-max

nextlevelbuilder

"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."

1,2691,335

drawio-diagrams-enhanced

jgtolentino

Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.

1,5441,153

godot

bfollington

This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.

1,358809

nano-banana-pro

garg-aayush

Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.

1,264728

pdf-to-markdown

aliceisjustplaying

Convert entire PDF documents to clean, structured Markdown for full context loading. Use this skill when the user wants to extract ALL text from a PDF into context (not grep/search), when discussing or analyzing PDF content in full, when the user mentions "load the whole PDF", "bring the PDF into context", "read the entire PDF", or when partial extraction/grepping would miss important context. This is the preferred method for PDF text extraction over page-by-page or grep approaches.

1,492684