improvement(performance): use redis for session data (#934)

This commit is contained in:
Waleed Latif
2025-08-11 20:42:22 -07:00
committed by GitHub
parent bc455d5bf4
commit 3c7b3e1a4b
2 changed files with 45 additions and 3 deletions

View File

@@ -25,6 +25,7 @@ import { quickValidateEmail } from '@/lib/email/validation'
import { env, isTruthy } from '@/lib/env'
import { isBillingEnabled, isProd } from '@/lib/environment'
import { createLogger } from '@/lib/logs/console/logger'
import { getRedisClient } from '@/lib/redis'
import { getEmailDomain } from '@/lib/urls/utils'
import { db } from '@/db'
import * as schema from '@/db/schema'
@@ -72,14 +73,55 @@ export const auth = betterAuth({
provider: 'pg',
schema,
}),
// Conditionally use Redis for session storage only if Redis is available
...(env.REDIS_URL
? {
secondaryStorage: {
get: async (key: string) => {
try {
const redis = getRedisClient()
if (!redis) return null
const value = await redis.get(`auth:${key}`)
return value || null
} catch (error) {
logger.error('Redis get error:', error)
return null
}
},
set: async (key: string, value: string, ttl?: number) => {
try {
const redis = getRedisClient()
if (!redis) return
if (ttl) {
await redis.setex(`auth:${key}`, ttl, value)
} else {
await redis.set(`auth:${key}`, value)
}
} catch (error) {
logger.error('Redis set error:', error)
}
},
delete: async (key: string) => {
try {
const redis = getRedisClient()
if (!redis) return
await redis.del(`auth:${key}`)
} catch (error) {
logger.error('Redis delete error:', error)
}
},
},
}
: {}),
session: {
cookieCache: {
enabled: true,
maxAge: 24 * 60 * 60, // 24 hours in seconds
// Use shorter cache with Redis (5 min), longer without (1 hour)
maxAge: env.REDIS_URL ? 5 * 60 : 60 * 60,
},
expiresIn: 30 * 24 * 60 * 60, // 30 days (how long a session can last overall)
updateAge: 24 * 60 * 60, // 24 hours (how often to refresh the expiry)
freshAge: 60 * 60, // 1 hour (or set to 0 to disable completely)
freshAge: env.REDIS_URL ? 0 : 6 * 60 * 60, // 0 with Redis, 6 hours without Redis
},
databaseHooks: {
session: {

View File

@@ -29,7 +29,7 @@ export const env = createEnv({
// Database & Storage
POSTGRES_URL: z.string().url().optional(), // Alternative PostgreSQL connection string
REDIS_URL: z.string().url().optional(), // Redis connection string for caching/sessions
REDIS_URL: z.string().url().optional(), // Redis connection string for caching/sessions (optional - improves performance)
// Payment & Billing
BILLING_ENABLED: z.boolean().optional(), // Enable billing enforcement and usage tracking