BetterAuth Implementation:
- β Password Hashing: BetterAuth uses bcrypt for password hashing with salt rounds
- β Session Management: 7-day expiration with 1-day update cycle (prevents token staleness)
- β Email Verification: Required before account activation
- β OAuth 2.0: Google and GitHub OAuth with proper PKCE flow
- β CSRF Protection: Built into Next.js 15 and BetterAuth
- β HTTP-only Cookies: Sessions stored in HTTP-only cookies (not accessible to JavaScript)
Turso/LibSQL Security:
- β End-to-End Encrypted: Transport security with TLS 1.3
- β Authentication Tokens: Per-database tokens with granular permissions
- β Row-Level Security: Can be implemented via application layer
- β Encrypted at Rest: Turso provides encryption for all stored data
- β Edge Distribution: Global replication with regional encryption
ConvexDB Security:
- β Automatic Authentication: Built-in user context in queries
- β Permission System: Server functions validate user permissions
- β Real-time Security: Subscriptions respect user permissions
- β API Keys: Secure API key generation for service-to-service auth
Next.js 15 Security Headers (configured in next.config.ts):
X-Frame-Options: DENY # Prevent clickjacking
X-Content-Type-Options: nosniff # Prevent MIME sniffing
Referrer-Policy: origin-when-cross-origin # Control referrer
Deployment (Vercel):
- β DDoS Protection: Vercel's global network includes DDoS mitigation
- β SSL/TLS: Automatic HTTPS for all deployments
- β WAF: Web Application Firewall protection
- β Rate Limiting: Built-in rate limiting on API routes
- β Environment Variables: Encrypted secrets management
BetterAuth API Routes (/api/auth/[...all]):
- β Rate Limiting: Configure in production
- β Input Validation: Zod schema validation
- β CORS: Properly configured for your domain
- β Method Validation: POST/GET validation per endpoint
Drizzle ORM:
- β Type-Safe Queries: TypeScript prevents SQL injection
- β Parameterized Queries: All queries use prepared statements
- β Schema Validation: Zod integration for runtime validation
Zod Schemas (setup ready):
// Example for additional validation
import { z } from "zod";
export const createUserSchema = z.object({
email: z.string().email(),
name: z.string().min(2).max(100),
password: z.string().min(8),
});-
Generate Strong Secrets
openssl rand -base64 32 # BETTER_AUTH_SECRET -
Enable Email Verification
- Currently enabled in auth.ts
- Configure SMTP for production
-
Rate Limiting
// Add to API routes import { Ratelimit } from "@upstash/ratelimit";
-
API Key Security
- Hash API keys before storage
- Rotate keys regularly
- Monitor key usage
-
Audit Logging
- All admin actions logged to
adminAuditLogs - Review logs regularly
- Archive old logs
- All admin actions logged to
-
Environment Variables
- Never commit
.env.local - Use Vercel's environment variable management
- Rotate secrets quarterly
- Never commit
-
CORS Configuration Update
next.config.ts:async headers() { return [{ source: '/api/(.*)', headers: [ { key: 'Access-Control-Allow-Origin', value: process.env.ALLOWED_ORIGIN }, { key: 'Access-Control-Allow-Methods', value: 'GET,POST,PUT,DELETE' }, ], }]; }
β Headless CMS: Provides content API without coupled frontend β Type-Safe: Full TypeScript support matches your backend β Database Agnostic: Works with Turso/SQLite without issues β Access Control: Built-in role-based access control β REST & GraphQL: Multiple API options β Webhook Support: Integrates with ConvexDB for sync
Option 1: Unified Authentication (Recommended)
// In payload.config.ts
import { auth } from "@/lib/auth";
export default buildConfig({
// ...
middleware: [
async (req, res, next) => {
// Check BetterAuth session
const session = await auth.api.getSession({
headers: req.headers,
});
if (session?.user?.isSuperAdmin) {
// Allow admin access to PayloadCMS
req.user = session.user;
}
next();
},
],
});Option 2: Separate PayloadCMS Auth
// PayloadCMS has its own built-in authentication
// Use email/password credentials separate from main app
// Can sync users between systems-
Create Separate Database for PayloadCMS
turso db create bytestack-cms turso db tokens create bytestack-cms
-
Environment Variables
PAYLOAD_TURSO_URL=libsql://your-cms-db.turso.io PAYLOAD_TURSO_TOKEN=your_cms_token PAYLOAD_SECRET=your_payload_secret # For encryption
-
Access Control in PayloadCMS
// In collections/Posts.ts access: { read: ({ req }) => { if (req.user?.role === 'admin') return true; return { author: { equals: req.user?.id } }; }, update: ({ req }) => req.user?.role === 'admin', delete: ({ req }) => req.user?.role === 'superadmin', }
ConvexDB β Turso Sync (via DataSyncService):
1. User creates content in app
2. ConvexDB updates real-time
3. Sync service periodically syncs to Turso
4. PayloadCMS reads from Turso
PayloadCMS β ConvexDB Sync (webhook):
1. Admin updates content in PayloadCMS
2. Webhook notifies app
3. App updates ConvexDB
4. Real-time updates propagate
// src/lib/payload-integration.ts
import payload from "payload";
export async function syncContentToConvex() {
// Get all posts from PayloadCMS
const posts = await payload.find({
collection: "posts",
});
// Update ConvexDB via mutation
for (const post of posts.docs) {
// Your ConvexDB sync logic
}
}| Vulnerability | Status | Mitigation |
|---|---|---|
| SQL Injection | β Protected | Drizzle ORM + parameterized queries |
| XSS | β Protected | React escaping + Next.js CSP headers |
| CSRF | β Protected | BetterAuth + Next.js middleware |
| Session Hijacking | β Protected | HTTP-only cookies + 7-day expiry |
| Password Exposure | β Protected | Bcrypt hashing + email verification |
| API Key Leaks | Hash keys, rotate regularly, monitor usage | |
| SSRF | β Protected | Server-side validation in API routes |
| Rate Limiting | Add Upstash/Redis rate limiting | |
| DDoS | β Protected | Vercel's global network protection |
Before going to production:
- Enable email verification in production SMTP
- Generate new BETTER_AUTH_SECRET for production
- Configure rate limiting for API routes
- Set up monitoring and alerting
- Enable audit logging for admin actions
- Configure CORS properly for your domain
- Set up regular security updates for dependencies
- Enable 2FA for superadmin accounts
- Configure backup strategy for Turso databases
- Set up penetration testing
- Review and test PayloadCMS access controls
- Document security procedures for team