engineering-betterauth-integration
Use when implementing authentication, login flows, OAuth, JWT sessions, or role-based access control (RBAC) for games with BetterAuth. Triggers: auth, login, OAuth, JWT, roles, permissions, RBAC.
Best use case
engineering-betterauth-integration is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
Use when implementing authentication, login flows, OAuth, JWT sessions, or role-based access control (RBAC) for games with BetterAuth. Triggers: auth, login, OAuth, JWT, roles, permissions, RBAC.
Teams using engineering-betterauth-integration should expect a more consistent output, faster repeated execution, less prompt rewriting.
When to use this skill
- You want a reusable workflow that can be run more than once with consistent structure.
When not to use this skill
- You only need a quick one-off answer and do not need a reusable workflow.
- You cannot install or maintain the underlying files, dependencies, or repository context.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/betterauth-integration/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How engineering-betterauth-integration Compares
| Feature / Agent | engineering-betterauth-integration | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
Use when implementing authentication, login flows, OAuth, JWT sessions, or role-based access control (RBAC) for games with BetterAuth. Triggers: auth, login, OAuth, JWT, roles, permissions, RBAC.
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
SKILL.md Source
# BetterAuth Integration
## Purpose
Auth flows, session management, OAuth, JWT, RBAC for game players/admins/mods using BetterAuth with Elysia + Drizzle ORM.
## When to Use
Trigger: auth, authentication, login, signup, OAuth, JWT, session, RBAC, roles, permissions, player auth, admin auth, moderator, BetterAuth
## Prerequisites
- `postgres-game-schema` (for user tables)
## Core Principles
> "Security is not a feature. It's a foundation." — OWASP
> "Trust is the currency of multiplayer games." — Raph Koster
1. **Auth is not optional** — every game endpoint must be authenticated
2. **Role-based access: player, moderator, admin** with escalating privileges
3. **Session tokens over JWTs for web games** — stateful > stateless for games (revocable, server-controlled)
4. **OAuth for social login** — Discord, Google, GitHub, Twitch are standard for gamers
5. **Rate limit auth endpoints aggressively** — prevent brute force and credential stuffing
6. **Never store passwords** — BetterAuth handles hashing with bcrypt/argon2
7. **Separate game sessions from auth sessions** — auth session = "who you are", game session = "what room you're in"
## Step-by-Step Instructions
### 1. Install Dependencies
```bash
bun add better-auth drizzle-orm @neondatabase/serverless
bun add -d drizzle-kit @types/bun
```
### 2. Configure BetterAuth
Create the auth instance with Drizzle adapter, OAuth providers, and custom user fields. See `boilerplate/auth-setup.ts` for the complete configuration.
### 3. Add Auth Middleware to Elysia
Mount the BetterAuth handler and add session/role middleware to your Elysia app. See `boilerplate/auth-middleware.ts` for `requireAuth`, `requireRole`, and `optionalAuth` patterns.
### 4. Define Roles and Permissions
Set up the RBAC system with role enums and permission maps. See `templates/role-definitions.ts` for the full type definitions and permission matrix.
### 5. Mount Auth Routes
Add standard auth routes (signup, login, logout, OAuth, session, admin). See `templates/auth-routes.ts` for the route patterns.
### 6. Generate Auth Tables
BetterAuth manages its own tables. Run migrations after setup:
```bash
bunx drizzle-kit generate
bunx drizzle-kit migrate
```
### 7. Protect Game Endpoints
Apply middleware to all game routes:
```typescript
import { requireAuth, requireRole } from './auth-middleware';
app
.use(requireAuth)
.get('/api/game/state', ({ user }) => getGameState(user.id))
.use(requireRole('admin'))
.delete('/api/game/reset', () => resetGame());
```
## Code Examples
### Basic auth check in a route
```typescript
import { auth } from './auth-setup';
app.get('/api/me', async ({ headers }) => {
const session = await auth.api.getSession({ headers });
if (!session) return { error: 'Not authenticated' };
return { user: session.user };
});
```
### Protecting a WebSocket connection
```typescript
// Validate session before upgrading to WebSocket
app.ws('/ws', {
async beforeHandle({ headers }) {
const session = await auth.api.getSession({ headers });
if (!session) throw new Error('Unauthorized');
},
// ... ws handlers
});
```
### Checking role before an action
```typescript
import { hasPermission } from './role-definitions';
app.delete('/api/players/:id/ban', async ({ user, params }) => {
if (!hasPermission(user.role, 'users', 'ban')) {
return { error: 'Insufficient permissions' };
}
await banPlayer(params.id, user.id);
return { banned: true };
});
```
See `boilerplate/auth-setup.ts` and `boilerplate/auth-middleware.ts` for full implementation patterns.
## Cross-References
- `postgres-game-schema` for user/player table schemas
- `game-backend-architecture` for Elysia server setup and route structure
- `redis-game-patterns` for session caching and rate limiting
- `stripe-game-payments` for authenticated payment flows
## Pitfalls & Anti-Patterns
- **Don't roll your own password hashing** — BetterAuth handles this with battle-tested algorithms; never store plaintext or MD5
- **Don't use JWTs as the sole session mechanism for web games** — they can't be revoked server-side; use BetterAuth's session tokens with cookie storage
- **Don't skip rate limiting on auth endpoints** — `/auth/login` and `/auth/signup` are prime brute force targets; limit to 5-10 attempts per minute
- **Don't store roles in the JWT/token** — always fetch the current role from the database to ensure role changes take effect immediately
- **Don't use a single "admin" boolean** — use a proper role enum (player/moderator/admin) so permissions can be granularly assigned
- **Don't mix auth sessions with game sessions** — a player can be logged in (auth session) without being in a match (game session); these are separate concerns
- **Don't trust client-sent user IDs** — always derive the user identity from the server-validated session, never from request body/params
- **Don't forget CORS configuration** — OAuth redirects and cookie-based sessions require correct origin settings
## Designer Philosophy
Security enables trust; trust enables social gameplay. When players know their accounts are safe, they invest more in the game — socially, economically, and emotionally. Authentication is invisible when done right: players log in once, stay logged in, and never think about it again. Every friction point in auth is a player lost.
## Sources
- [BetterAuth Documentation](https://www.better-auth.com/docs)
- [OWASP Authentication Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html)
- [OWASP Session Management Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html)
- [Elysia Documentation](https://elysiajs.com)
- [Drizzle ORM Documentation](https://orm.drizzle.team)Related Skills
infrastructure-cursor-codex-integration
Use when configuring Cursor IDE or OpenAI Codex for game development — .cursorrules files, prompt conventions, context injection. Triggers: cursor, .cursorrules, codex, IDE setup.
engineering-stripe-game-payments
Use when implementing game payments, in-app purchases, subscriptions, Stripe webhooks, or monetization flows. Triggers: payments, IAP, subscription, Stripe, checkout, webhooks, monetization.
engineering-redis-game-patterns
Use when implementing Redis patterns for games — caching, leaderboards, pub/sub messaging, session storage, rate limiting, or ephemeral game state. Triggers: Redis, cache, leaderboard, pub/sub, rate limit, session.
engineering-postgres-game-schema
Use when designing game database schemas, player data models, inventory systems, or working with Drizzle ORM and PostgreSQL for games. Triggers: database, schema, Drizzle, players, inventory, leaderboards, game data.
engineering-matchmaking-system
Use when implementing player matchmaking, skill-based match selection, lobby systems, queue management, or rank-based grouping. Triggers: matchmaking, lobby, queue, ELO, skill-based, rank, match players, pairing, bracket.
engineering-gameplay-analytics
Use when tracking player events, implementing retention analytics, building engagement funnels, measuring D1/D7/D30 retention, or setting up gameplay telemetry. Triggers: analytics, telemetry, events, retention, D1 D7 D30, funnel, engagement, session tracking, player behavior.
engineering-game-state-sync
Use when implementing client-server state synchronization, delta compression, optimistic updates, rollback netcode, or real-time game state reconciliation. Triggers: state sync, netcode, delta, rollback, interpolation, prediction.
engineering-game-backend-architecture
Use when building game servers, WebSocket connections, room management, game tick loops, or server-authoritative architecture with Elysia. Triggers: game server, WebSocket, rooms, tick loop, server architecture, multiplayer backend.
engineering-elevenlabs-sound-music
Use when adding audio to a game — SFX generation, adaptive music, voice acting, and audio state machine integration. Covers BOTH ElevenLabs API AND Vertex AI Lyria as user-choosable alternatives for game audio production.
engineering-bullmq-game-queues
Use when implementing job queues, matchmaking systems, async game events, delayed jobs, or scheduled tasks with BullMQ. Triggers: queue, matchmaking, async events, jobs, workers, scheduling.
react-animations
Use when implementing animations, transitions, or motion effects in React apps. Invoke this skill whenever someone asks about animation, transition, motion, framer motion, react spring, GSAP, entrance/exit effects, scroll animation, parallax, gesture, drag, card flip, screen shake, health bar, damage numbers, loading states, page transitions, hover effects, or any element that should move, fade, scale, or respond to interaction — even if they don't use the word "animation".
openclaw-genie
Use when the user asks about OpenClaw — installation, configuration, agents, channels, memory, tools, hooks, skills, deployment, Docker, multi-agent, OAuth, gateway, CLI, browser, exec, PDF, voice, secrets, sandboxing, sessions, cron, webhooks, heartbeat, sub-agents, nodes, companion devices, canvas, camera, or messaging platform integration. Also invoke for questions about running OpenClaw agents: memory recall (memory_search), cron scheduling, multi-agent setup, or any openclaw.json behavior. OpenClaw has proprietary configuration syntax (SecretRef, dmPolicy, node.invoke, tool profiles) and CLI commands that require this skill to answer correctly.