Better Auth
Add secure authentication to your MCP server using Better Auth and PostgreSQL
Overview
The Better Auth plugin provides comprehensive authentication for your xmcp server using Better Auth, supporting email/password authentication, OAuth providers, and session management.
Currently supports PostgreSQL as the database provider.
Installation
Install the Better Auth plugin and PostgreSQL dependencies:
Database Setup
Better Auth requires a PostgreSQL database with specific tables for user management, sessions, and OAuth applications.
We recommend Neon for easy PostgreSQL setup, especially with Vercel's storage integration.
Run the following SQL script to create the necessary tables:
Schema generation through Better Auth's CLI is not currently supported. You must run this SQL manually.
Environment Variables
Configure the following environment variables in your .env file:
Generate a strong, random secret for BETTER_AUTH_SECRET. This is used to
sign JWT tokens and must be kept secure.
Configuration
Create a middleware.ts file in your xmcp app root directory:
Configuration Options
database- PostgreSQL Pool instance for database connectionsbaseURL- Base URL of your app for generating OAuth callback URLssecret- Secret key for signing JWT tokensproviders- Authentication provider configuration
Authentication Providers
Email and Password
Enable email/password authentication:
Google OAuth
To enable Google OAuth:
- Visit the Google Cloud Console
- Create or select a project
- Enable the Google+ API
- Create OAuth 2.0 credentials
- Set authorized redirect URI:
- Development:
http://localhost:3001/auth/callback/google - Production:
https://yourdomain.com/auth/callback/google
- Development:
Multiple Providers
You can enable multiple authentication methods simultaneously:
Usage in Tools
Access the authenticated user session in your xmcp tools using getBetterAuthSession:
getBetterAuthSession will throw an error if called outside of a
betterAuthProvider middleware context.
Login Page
The authentication UI is automatically generated and available at:
This page handles both sign-in and sign-up functionality based on your provider configuration.
Next Steps
After authentication is configured, users will be prompted to authenticate when establishing a connection to your MCP server.