docs/src/content/en/reference/auth/better-auth.mdx
The MastraAuthBetterAuth class provides authentication for Mastra applications using Better Auth. It verifies incoming requests with Better Auth sessions and integrates with the Mastra server using the auth option.
import { Mastra } from '@mastra/core'
import { MastraAuthBetterAuth } from '@mastra/auth-better-auth'
import { betterAuth } from 'better-auth'
// Create your Better Auth instance
const auth = betterAuth({
database: {
provider: 'postgresql',
url: process.env.DATABASE_URL,
},
emailAndPassword: {
enabled: true,
},
baseURL: process.env.BETTER_AUTH_URL,
secret: process.env.BETTER_AUTH_SECRET,
})
export const mastra = new Mastra({
server: {
auth: new MastraAuthBetterAuth({
auth,
}),
},
})
<PropertiesTable content={[ { name: 'auth', type: 'Auth', description: 'Your Better Auth instance created via betterAuth({ ... }). This is required and must be properly configured with a supported database provider.', isOptional: false, }, { name: 'name', type: 'string', description: 'Custom name for the auth provider instance.', isOptional: true, defaultValue: "'better-auth'", }, { name: 'authorizeUser', type: '(user: BetterAuthUser, request: HonoRequest) => Promise<boolean> | boolean', description: 'Custom authorization function to determine if a user should be granted access. Called after session verification. By default, allows all authenticated users with valid sessions.', isOptional: true, }, { name: 'public', type: 'Array<string | RegExp | [string, Methods | Methods[]]>', description: 'Public routes that do not require authentication. Supports exact paths, wildcards, and path params.', isOptional: true, }, { name: 'protected', type: 'Array<string | RegExp | [string, Methods | Methods[]]>', description: 'Protected routes that require authentication. Supports exact paths, wildcards, and path params.', isOptional: true, }, ]} />
BetterAuthUser typeThe BetterAuthUser type contains the session and user information returned by Better Auth:
interface BetterAuthUser {
session: Session
user: User
}
session: The Better Auth session object containing session metadatauser: The authenticated user object with user detailsThe Session and User types are exported by the Better Auth package.
public and protected accept exact paths, wildcard patterns (like /api/*), and path params (like /users/:id).["/api/agents", ["GET", "POST"]].public and protected, public wins and no auth is required.requiresAuth: false).