auth/better-auth/README.md
Better Auth integration for Mastra - a self-hosted, open-source authentication solution.
npm install @mastra/auth-better-auth better-auth
import { betterAuth } from 'better-auth';
import { MastraAuthBetterAuth } from '@mastra/auth-better-auth';
import { Mastra } from '@mastra/core';
// Create your Better Auth instance
const auth = betterAuth({
database: {
provider: 'postgresql',
url: process.env.DATABASE_URL!,
},
emailAndPassword: {
enabled: true,
},
});
// Create the Mastra auth provider
const mastraAuth = new MastraAuthBetterAuth({
auth,
});
// Use with Mastra
const mastra = new Mastra({
server: {
auth: mastraAuth,
},
});
| Option | Type | Required | Description |
|---|---|---|---|
auth | Auth | Yes | Your Better Auth instance created via betterAuth({ ... }) |
name | string | No | Custom name for the auth provider (default: 'better-auth') |
authorizeUser | (user, request) => Promise<boolean> | No | Custom authorization logic |
public | string[] | No | Public routes that don't require authentication |
protected | string[] | No | Protected routes that require authentication |
You can provide custom authorization logic:
const mastraAuth = new MastraAuthBetterAuth({
auth,
async authorizeUser(user) {
// Only allow verified emails
return user?.user?.emailVerified === true;
},
});
const mastraAuth = new MastraAuthBetterAuth({
auth,
async authorizeUser(user) {
// Check for admin role (assuming you have a role field)
const userWithRole = user?.user as any;
return userWithRole?.role === 'admin';
},
});
const mastraAuth = new MastraAuthBetterAuth({
auth,
public: ['/health', '/api/status'],
protected: ['/api/*', '/admin/*'],
});
Better Auth is a self-hosted, open-source authentication framework that gives you:
Apache-2.0