home / skills / jeremylongshore / claude-code-plugins-plus-skills / clerk-local-dev-loop

This skill helps you configure a local Clerk development loop, enabling test users, hot reload, and mock authentication for productive testing.

npx playbooks add skill jeremylongshore/claude-code-plugins-plus-skills --skill clerk-local-dev-loop

Review the files below or copy the command above to add this skill to your agents.

Files (1)
SKILL.md
4.1 KB
---
name: clerk-local-dev-loop
description: |
  Set up local development workflow with Clerk.
  Use when configuring development environment, testing auth locally,
  or setting up hot reload with Clerk.
  Trigger with phrases like "clerk local dev", "clerk development",
  "test clerk locally", "clerk dev environment".
allowed-tools: Read, Write, Edit, Bash(npm:*), Bash(pnpm:*), Grep
version: 1.0.0
license: MIT
author: Jeremy Longshore <[email protected]>
---

# Clerk Local Dev Loop

## Overview
Configure an efficient local development workflow with Clerk authentication.

## Prerequisites
- Clerk SDK installed
- Development and production instances in Clerk dashboard
- Node.js development environment

## Instructions

### Step 1: Configure Development Instance
```bash
# Use development keys in .env.local
cat > .env.local << 'EOF'
# Development keys (start with pk_test_ and sk_test_)
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_...
CLERK_SECRET_KEY=sk_test_...

# Optional: Custom sign-in/sign-up URLs
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
EOF
```

### Step 2: Set Up Test Users
```typescript
// scripts/create-test-user.ts
// Use Clerk Backend SDK for test user management
import { clerkClient } from '@clerk/nextjs/server'

async function createTestUser() {
  const user = await clerkClient.users.createUser({
    emailAddress: ['[email protected]'],
    password: 'testpassword123',
    firstName: 'Test',
    lastName: 'User'
  })
  console.log('Created test user:', user.id)
}
```

### Step 3: Configure Hot Reload
```typescript
// next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
  // Clerk works with fast refresh out of the box
  reactStrictMode: true,

  // Environment-specific configuration
  env: {
    CLERK_DOMAIN: process.env.NODE_ENV === 'development'
      ? 'clerk.your-dev-domain.com'
      : 'clerk.your-prod-domain.com'
  }
}

module.exports = nextConfig
```

### Step 4: Development Scripts
```json
{
  "scripts": {
    "dev": "next dev",
    "dev:https": "next dev --experimental-https",
    "clerk:dev": "npx @clerk/cli dev",
    "test:auth": "node scripts/test-auth.js"
  }
}
```

### Step 5: Mock Authentication for Tests
```typescript
// __tests__/setup.ts
import { vi } from 'vitest'

// Mock Clerk for unit tests
vi.mock('@clerk/nextjs', () => ({
  auth: () => ({ userId: 'test-user-id' }),
  currentUser: () => ({
    id: 'test-user-id',
    firstName: 'Test',
    emailAddresses: [{ emailAddress: '[email protected]' }]
  }),
  useUser: () => ({
    user: { id: 'test-user-id', firstName: 'Test' },
    isLoaded: true,
    isSignedIn: true
  })
}))
```

## Output
- Development environment configured
- Test users available
- Hot reload working with auth
- Mocked auth for testing

## Error Handling
| Error | Cause | Solution |
|-------|-------|----------|
| Development/Production mismatch | Using prod keys in dev | Use pk_test_/sk_test_ keys locally |
| SSL Required | Clerk needs HTTPS | Use `next dev --experimental-https` |
| Cookies Not Set | Wrong domain config | Check Clerk dashboard domain settings |
| Session Not Persisting | LocalStorage issues | Clear browser storage, check domain |

## Examples

### Environment Switching
```typescript
// lib/clerk.ts
export const clerkConfig = {
  publishableKey: process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY!,
  signInUrl: process.env.NEXT_PUBLIC_CLERK_SIGN_IN_URL || '/sign-in',
  signUpUrl: process.env.NEXT_PUBLIC_CLERK_SIGN_UP_URL || '/sign-up',
}

// Validate configuration
if (!clerkConfig.publishableKey.startsWith('pk_')) {
  throw new Error('Invalid Clerk publishable key')
}
```

### Local Webhook Testing
```bash
# Use ngrok or similar for webhook testing
npx ngrok http 3000

# Update webhook URL in Clerk dashboard to ngrok URL
# https://abc123.ngrok.io/api/webhooks/clerk
```

## Resources
- [Clerk Development Mode](https://clerk.com/docs/deployments/overview)
- [Test Mode](https://clerk.com/docs/testing/overview)
- [CLI Tools](https://clerk.com/docs/references/cli)

## Next Steps
Proceed to `clerk-sdk-patterns` for common SDK usage patterns.

Overview

This skill sets up a fast, reliable local development loop with Clerk authentication so you can build and test auth flows locally. It guides configuration of development keys, test users, hot reload integration, and mocked auth for unit tests. The outcome is a reproducible dev environment with working sessions, test accounts, and webhook/testing tips.

How this skill works

It configures environment variables for Clerk development keys and optional custom routes, adds scripts to run Clerk locally and start Next.js with HTTPS, and shows how to create test users via the Clerk backend SDK. It also includes examples to enable hot reload with environment-specific domain settings and provides mocks to simulate authenticated users in unit tests.

When to use it

  • Setting up a local dev environment that uses Clerk for authentication
  • Testing sign-in, sign-up, and session flows before deployment
  • Running automated tests that require authenticated contexts
  • Building onboarding flows that depend on Clerk webhooks or redirects
  • Debugging domain/cookie issues or SSL-related Clerk errors

Best practices

  • Keep development keys (pk_test_/sk_test_) in a local .env file and never commit them
  • Run Clerk CLI or ngrok to expose local URLs for webhook testing
  • Create dedicated test users via the backend SDK to recreate real workflows
  • Mock Clerk in unit tests to avoid network calls and keep tests deterministic
  • Use environment-specific domain config to prevent cookie and session mismatches

Example use cases

  • Configure .env.local with NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY and CLERK_SECRET_KEY for local dev
  • Run npx @clerk/cli dev alongside next dev to emulate Clerk services locally
  • Create test users programmatically with clerkClient.users.createUser for integration testing
  • Enable next dev --experimental-https or use ngrok to satisfy Clerk’s HTTPS requirement
  • Mock @clerk/nextjs in Vitest/Jest to simulate signed-in users during unit tests

FAQ

What keys should I use for local development?

Use Clerk test mode keys that start with pk_test_ and sk_test_. Store them in a local .env file and do not push them to source control.

How do I test webhooks locally?

Expose your local server with ngrok (or similar), update the webhook URL in Clerk dashboard to the ngrok address, and forward requests to your /api/webhooks/clerk endpoint.

Why is my session not persisting locally?

Check that you are using the correct development domain in env config, that cookies are allowed for that domain, and consider running with HTTPS to meet Clerk requirements.