Clerk Authentication for Mastra

Trust: ★★★☆☆ (0.90) · 0 validations · developer_reference

Published: 2026-05-10 · Source: crawler_authoritative

Tình huống

Guide for integrating Clerk authentication with Mastra agents, targeting developers configuring user authentication for their Mastra applications.

Insight

The @mastra/auth-clerk package provides authentication for Mastra using Clerk. It verifies incoming requests using Clerk’s authentication system and integrates with the Mastra server using the auth option. The MastraAuthClerk class accepts three required configuration options: publishableKey (CLERK_PUBLISHABLE_KEY), secretKey (CLERK_SECRET_KEY), and jwksUri (CLERK_JWKS_URI). These credentials are found in the Clerk Dashboard under API Keys. The JWKS URI follows the pattern https://your-clerk-domain.clerk.accounts.dev/.well-known/jwks.json. The default authorizeUser method allows all authenticated users, but a custom authorizeUser function can be provided for customized authorization logic. On the client side, users must retrieve the Clerk access token using the useAuth hook from @clerk/nextjs and include it in the Authorization header as a Bearer token.

Hành động

Install the package using npm install @mastra/auth-clerk@latest, pnpm add @mastra/auth-clerk@latest, yarn add @mastra/auth-clerk@latest, or bun add @mastra/auth-clerk@latest. Add credentials to .env file: CLERK_PUBLISHABLE_KEY, CLERK_SECRET_KEY, and CLERK_JWKS_URI. Configure MastraAuthClerk in the Mastra server config with the publishableKey, secretKey, and jwksUri options. On the client side, use the Clerk useAuth hook to get the access token via getToken(), then include it in MastraClient headers as Authorization: Bearer ${token}. All requests with auth enabled must include a valid Clerk access token. For React components, instantiate MastraClient inside functions after obtaining the token.

Kết quả

Returns authenticated requests validated against Clerk’s authentication system, with access token included in the Authorization header enabling user-specific agent interactions.

Điều kiện áp dụng

Requires @mastra/auth-clerk package installation. Works with Mastra server auth configuration. Client-side requires @clerk/nextjs for React applications.


Nội dung gốc (Original)

Clerk

The @mastra/auth-clerk package provides authentication for Mastra using Clerk. It verifies incoming requests using Clerk’s authentication system and integrates with the Mastra server using the auth option.

Prerequisites

This example uses Clerk authentication. Make sure to add your Clerk credentials to your .env file and ensure your Clerk project is properly configured.

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

Note: You can find these keys in your Clerk Dashboard under “API Keys”.

Installation

Before you can use the MastraAuthClerk class you have to install the @mastra/auth-clerk package.

npm:

npm install @mastra/auth-clerk@latest

pnpm:

pnpm add @mastra/auth-clerk@latest

Yarn:

yarn add @mastra/auth-clerk@latest

Bun:

bun add @mastra/auth-clerk@latest

Usage example

import { Mastra } from '@mastra/core'
import { MastraAuthClerk } from '@mastra/auth-clerk'
 
export const mastra = new Mastra({
  server: {
    auth: new MastraAuthClerk({
      publishableKey: process.env.CLERK_PUBLISHABLE_KEY,
      secretKey: process.env.CLERK_SECRET_KEY,
      jwksUri: process.env.CLERK_JWKS_URI,
    }),
  },
})

Info: The default authorizeUser method allows all authenticated users. To customize user authorization, provide a custom authorizeUser function when constructing the provider.

Visit MastraAuthClerk for all available configuration options.

Client-side setup

When using Clerk auth, you’ll need to retrieve the access token from Clerk on the client side and pass it to your Mastra requests.

Retrieving the access token

Use the Clerk React hooks to authenticate users and retrieve their access token:

import { useAuth } from '@clerk/nextjs'
 
export const useClerkAuth = () => {
  const { getToken } = useAuth()
 
  const getAccessToken = async () => {
    const token = await getToken()
    return token
  }
 
  return { getAccessToken }
}

Info: Refer to the Clerk documentation for more information.

Configuring MastraClient

When auth is enabled, all requests made with MastraClient must include a valid Clerk access token in the Authorization header:

import { MastraClient } from '@mastra/client-js'
 
export const mastraClient = new MastraClient({
  baseUrl: 'https://<mastra-api-url>',
  headers: {
    Authorization: `Bearer ${accessToken}`,
  },
})

Info: The access token must be prefixed with Bearer in the Authorization header.

Visit Mastra Client SDK for more configuration options.

Making authenticated requests

Once MastraClient is configured with the Clerk access token, you can send authenticated requests:

React:

'use client'
 
import { useAuth } from '@clerk/nextjs'
import { MastraClient } from '@mastra/client-js'
 
export const TestAgent = () => {
  const { getToken } = useAuth()
 
  async function handleClick() {
    const token = await getToken()
 
    const client = new MastraClient({
      baseUrl: 'http://localhost:4111',
      headers: token ? { Authorization: `Bearer ${token}` } : undefined,
    })
 
    const weatherAgent = client.getAgent('weatherAgent')
    const response = await weatherAgent.generate("What's the weather like in New York")
 
    console.log({ response })
  }
 
  return <button onClick={handleClick}>Test Agent</button>
}

cURL:

curl -X POST http://localhost:4111/api/agents/weatherAgent/generate \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer <your-clerk-access-token>" \
  -d '{
    "messages": "Weather in London"
  }'

Liên kết

Xem thêm: