Skip to main content
Clerk provides complete user management and authentication with pre-built UI components and powerful APIs.

Installation

npm install @mastra/auth-clerk

Configuration

1

Get Clerk Credentials

Sign up at Clerk and create an application. Get your:
  • Secret Key
  • Publishable Key
  • JWKS URI (from the API Keys page)
2

Set Environment Variables

.env
CLERK_SECRET_KEY=sk_test_...
CLERK_PUBLISHABLE_KEY=pk_test_...
CLERK_JWKS_URI=https://your-domain.clerk.accounts.dev/.well-known/jwks.json
3

Import and Configure

import { MastraAuthClerk } from '@mastra/auth-clerk';
import { Mastra } from '@mastra/core';

const auth = new MastraAuthClerk();

const mastra = new Mastra({
  server: {
    auth,
  },
});

Configuration Options

secretKey
string
Clerk secret key. Defaults to process.env.CLERK_SECRET_KEY
publishableKey
string
Clerk publishable key. Defaults to process.env.CLERK_PUBLISHABLE_KEY
jwksUri
string
JWKS URI for token verification. Defaults to process.env.CLERK_JWKS_URI
name
string
default:"clerk"
Provider name identifier

Usage Examples

Basic Setup

import { Mastra } from '@mastra/core';
import { MastraAuthClerk } from '@mastra/auth-clerk';
import { MastraServer } from '@mastra/hono';
import { Hono } from 'hono';

const mastra = new Mastra({
  server: {
    auth: new MastraAuthClerk(),
  },
});

const app = new Hono();
const server = new MastraServer({ mastra, app });

// All routes are now protected by Clerk authentication

Explicit Configuration

const auth = new MastraAuthClerk({
  secretKey: process.env.CLERK_SECRET_KEY!,
  publishableKey: process.env.CLERK_PUBLISHABLE_KEY!,
  jwksUri: process.env.CLERK_JWKS_URI!,
  name: 'clerk-auth',
});

const mastra = new Mastra({
  server: {
    auth,
  },
});

Custom Authorization

const auth = new MastraAuthClerk({
  authorizeUser: async (user) => {
    // Custom authorization logic
    return user.sub.startsWith('user_') && user.email_verified === true;
  },
});

const mastra = new Mastra({
  server: {
    auth,
  },
});

Client Integration

React with Clerk

import { ClerkProvider, SignedIn, SignedOut, SignInButton, UserButton } from '@clerk/nextjs';

export default function App() {
  return (
    <ClerkProvider>
      <SignedIn>
        <UserButton />
        <MyMastraComponent />
      </SignedIn>
      <SignedOut>
        <SignInButton />
      </SignedOut>
    </ClerkProvider>
  );
}

Making Authenticated Requests

import { useAuth } from '@clerk/nextjs';

function MyMastraComponent() {
  const { getToken } = useAuth();

  const callMastraAPI = async () => {
    const token = await getToken();

    const response = await fetch('http://localhost:4111/api/mastra/agents', {
      headers: {
        'Authorization': `Bearer ${token}`,
      },
    });

    const data = await response.json();
    console.log(data);
  };

  return <button onClick={callMastraAPI}>Call Mastra</button>;
}

Token Verification

Mastra automatically verifies Clerk JWT tokens:
  1. Token Extraction: Bearer token from Authorization header
  2. JWKS Verification: Validates token signature using Clerk’s JWKS endpoint
  3. Claims Validation: Checks token expiration and issuer
  4. Authorization: Calls custom authorizeUser function if provided

User Object

The authenticated user object contains standard JWT claims:
interface ClerkUser {
  sub: string; // User ID
  email?: string;
  email_verified?: boolean;
  name?: string;
  picture?: string;
  // ... other JWT claims
}

Authentication Flow

Best Practices

Use Environment Variables

Store Clerk credentials in environment variables, never hardcode them.

Enable Email Verification

Require email verification in your authorization logic for added security.

Token Expiration

Tokens expire automatically. Use Clerk’s session management to refresh tokens.

Production Keys

Use separate Clerk applications for development and production.

Clerk Features

Pre-built Components

Clerk provides ready-to-use UI components:
  • Sign In / Sign Up forms
  • User profile management
  • Multi-factor authentication
  • Social OAuth providers

Advanced Features

  • Organizations: Multi-tenant support
  • Roles & Permissions: Fine-grained access control
  • Sessions: Device-aware session management
  • Webhooks: Real-time user event notifications

Troubleshooting

Invalid JWKS URI

Ensure your JWKS URI matches your Clerk domain:
# Correct format
CLERK_JWKS_URI=https://your-app.clerk.accounts.dev/.well-known/jwks.json

Token Verification Failed

Check that:
  1. Token is not expired
  2. JWKS URI is correct
  3. Secret key matches your Clerk application

Missing Authorization Header

Ensure client includes Bearer token:
headers: {
  'Authorization': `Bearer ${token}`,
}

Auth0

Alternative enterprise identity platform

Supabase Auth

Open-source authentication

Clerk Documentation

Official Clerk documentation

Clerk Dashboard

Manage applications and users

Build docs developers (and LLMs) love