clerk-ci-integration

0
0
Source

Configure Clerk CI/CD integration with GitHub Actions and testing. Use when setting up automated testing, configuring CI pipelines, or integrating Clerk tests into your build process. Trigger with phrases like "clerk CI", "clerk GitHub Actions", "clerk automated tests", "CI clerk", "clerk pipeline".

Install

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

Installs to .claude/skills/clerk-ci-integration

About this skill

Clerk CI Integration

Overview

Set up CI/CD pipelines with Clerk authentication testing. Covers GitHub Actions workflows, Playwright E2E tests with Clerk auth, test user management, and CI secrets configuration.

Prerequisites

  • GitHub repository with Actions enabled
  • Clerk test API keys (pk_test_ / sk_test_)
  • npm/pnpm project configured

Instructions

Step 1: GitHub Actions Workflow

# .github/workflows/test.yml
name: Test with Clerk Auth
on:
  pull_request:
    branches: [main]
  push:
    branches: [main]

jobs:
  test:
    runs-on: ubuntu-latest
    env:
      NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY: ${{ secrets.CLERK_PK_TEST }}
      CLERK_SECRET_KEY: ${{ secrets.CLERK_SK_TEST }}
      CLERK_WEBHOOK_SECRET: ${{ secrets.CLERK_WEBHOOK_SECRET_TEST }}

    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: npm

      - run: npm ci
      - run: npm run build
      - run: npm test

      - name: Install Playwright
        run: npx playwright install --with-deps chromium

      - name: Run E2E tests
        run: npx playwright test
        env:
          CLERK_TEST_USER_EMAIL: ${{ secrets.CLERK_TEST_USER_EMAIL }}
          CLERK_TEST_USER_PASSWORD: ${{ secrets.CLERK_TEST_USER_PASSWORD }}

Step 2: Configure GitHub Secrets

Add these secrets in GitHub repo > Settings > Secrets:

SecretValue
CLERK_PK_TESTpk_test_... from dev instance
CLERK_SK_TESTsk_test_... from dev instance
CLERK_WEBHOOK_SECRET_TESTwhsec_... from dev webhooks
CLERK_TEST_USER_EMAILci-test@yourapp.com
CLERK_TEST_USER_PASSWORDStrong test password

Step 3: Playwright Auth Setup

// e2e/auth.setup.ts
import { test as setup, expect } from '@playwright/test'
import path from 'path'

const authFile = path.join(__dirname, '.auth/user.json')

setup('authenticate', async ({ page }) => {
  await page.goto('/sign-in')

  // Fill Clerk sign-in form
  await page.fill('input[name="identifier"]', process.env.CLERK_TEST_USER_EMAIL!)
  await page.click('button:has-text("Continue")')
  await page.fill('input[name="password"]', process.env.CLERK_TEST_USER_PASSWORD!)
  await page.click('button:has-text("Continue")')

  // Wait for redirect to authenticated page
  await page.waitForURL('/dashboard')
  await expect(page.locator('text=Dashboard')).toBeVisible()

  // Save auth state for reuse across tests
  await page.context().storageState({ path: authFile })
})

Step 4: Playwright Config with Auth State

// playwright.config.ts
import { defineConfig } from '@playwright/test'

export default defineConfig({
  testDir: './e2e',
  projects: [
    { name: 'setup', testMatch: 'auth.setup.ts' },
    {
      name: 'authenticated',
      testMatch: '*.spec.ts',
      dependencies: ['setup'],
      use: {
        storageState: 'e2e/.auth/user.json',
      },
    },
  ],
  webServer: {
    command: 'npm run dev',
    port: 3000,
    reuseExistingServer: !process.env.CI,
  },
})

Step 5: E2E Test Examples

// e2e/dashboard.spec.ts
import { test, expect } from '@playwright/test'

test('authenticated user sees dashboard', async ({ page }) => {
  await page.goto('/dashboard')
  await expect(page.locator('h1')).toContainText('Dashboard')
  await expect(page.locator('[data-clerk-user-button]')).toBeVisible()
})

test('unauthenticated user is redirected to sign-in', async ({ browser }) => {
  // Create fresh context without saved auth state
  const context = await browser.newContext()
  const page = await context.newPage()

  await page.goto('/dashboard')
  await expect(page).toHaveURL(/sign-in/)

  await context.close()
})

test('protected API returns data', async ({ page }) => {
  const response = await page.request.get('/api/data')
  expect(response.status()).toBe(200)
  const data = await response.json()
  expect(data.userId).toBeTruthy()
})

Step 6: Test User Seed Script for CI

// scripts/seed-ci-user.ts
import { createClerkClient } from '@clerk/backend'

const clerk = createClerkClient({ secretKey: process.env.CLERK_SECRET_KEY! })

async function ensureTestUser() {
  const email = process.env.CLERK_TEST_USER_EMAIL!
  const password = process.env.CLERK_TEST_USER_PASSWORD!

  const existing = await clerk.users.getUserList({ emailAddress: [email] })
  if (existing.totalCount > 0) {
    console.log('Test user already exists')
    return
  }

  await clerk.users.createUser({
    emailAddress: [email],
    password,
    firstName: 'CI',
    lastName: 'TestUser',
  })
  console.log('Test user created')
}

ensureTestUser()

Output

  • GitHub Actions workflow with Clerk env vars from secrets
  • Playwright auth setup saving session state for reuse
  • E2E tests covering authenticated and unauthenticated flows
  • Test user seed script for CI environments
  • Protected API endpoint test

Error Handling

ErrorCauseSolution
Secret not found in CIMissing GitHub secretAdd in repo Settings > Secrets and variables > Actions
Test user sign-in failsUser not created or wrong passwordRun seed script, verify credentials
Timeout on sign-in pageClerk SDK not loaded in CI buildEnsure NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY is set
E2E auth state staleCached session expiredDelete .auth/ directory, re-run setup

Examples

Vitest Unit Test with Mocked Clerk

// __tests__/api.test.ts
import { describe, it, expect, vi } from 'vitest'

vi.mock('@clerk/nextjs/server', () => ({
  auth: vi.fn().mockResolvedValue({ userId: 'user_test_123', has: () => true }),
}))

describe('Protected API', () => {
  it('returns data for authenticated user', async () => {
    const { GET } = await import('@/app/api/data/route')
    const response = await GET()
    expect(response.status).toBe(200)
  })
})

Resources

Next Steps

Proceed to clerk-deploy-integration for deployment platform setup.

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.

7824

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".

13615

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.

3114

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.

4311

performing-security-audits

jeremylongshore

This skill allows Claude to conduct comprehensive security audits of code, infrastructure, and configurations. It leverages various tools within the security-pro-pack plugin, including vulnerability scanning, compliance checking, cryptography review, and infrastructure security analysis. Use this skill when a user requests a "security audit," "vulnerability assessment," "compliance review," or any task involving identifying and mitigating security risks. It helps to ensure code and systems adhere to security best practices and compliance standards.

109

designing-database-schemas

jeremylongshore

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

1128

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.

9521,094

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.

846846

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."

571700

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.

548492

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.

673466

fastapi-templates

wshobson

Create production-ready FastAPI projects with async patterns, dependency injection, and comprehensive error handling. Use when building new FastAPI applications or setting up backend API projects.

514280

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.