@theiceji/authjs-prisma-redis-adapter
v1.0.1
Published
A high-performance Auth.js adapter that combines Prisma for database operations with Redis for session storage, providing the best of both worlds: reliable data persistence and fast session management.
Maintainers
Readme
@theiceji/authjs-prisma-redis-adapter
A high-performance Auth.js adapter that combines Prisma for database operations with Redis for session storage, providing the best of both worlds: reliable data persistence and fast session management.
Features
- Hybrid Storage: Prisma for user data, Redis for sessions
- Fast Sessions: Redis-based session storage with automatic TTL
- Secure: Full support for Auth.js security features
- Type Safe: Written in TypeScript with full type support
- Easy Integration: Drop-in replacement for standard Auth.js adapters
- Multi-Database: Works with any Prisma-supported database
Installation
npm install @theiceji/authjs-prisma-redis-adapter
# or
yarn add @theiceji/authjs-prisma-redis-adapter
# or
pnpm add @theiceji/authjs-prisma-redis-adapter
# or
bun add @theiceji/authjs-prisma-redis-adapterPeer Dependencies
Make sure you have the required peer dependencies installed:
npm install @auth/core @prisma/client ioredisQuick Start
1. Set up your Prisma schema
Your Prisma schema should include the standard Auth.js models:
model User {
id String @id @default(cuid())
name String?
email String @unique
emailVerified DateTime?
image String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
Accounts Account[]
Authenticators Authenticator[]
@@map("users")
}
model Account {
userId String
type String
provider String
providerAccountId String
refresh_token String?
access_token String?
expires_at Int?
token_type String?
scope String?
id_token String?
session_state String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
User User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@id([provider, providerAccountId])
@@map("accounts")
}
model VerificationToken {
identifier String
token String
expires DateTime
@@id([identifier, token])
@@map("verification_tokens")
}
model Authenticator {
credentialID String @unique
userId String
providerAccountId String
credentialPublicKey String
counter Int
credentialDeviceType String
credentialBackedUp Boolean
transports String?
User User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@id([userId, credentialID])
@@map("authenticators")
}2. Configure the adapter
// lib/auth.ts
import { PrismaRedisAdapter } from '@theiceji/authjs-prisma-redis-adapter'
import { PrismaClient } from '@prisma/client'
import { Redis } from 'ioredis'
const prisma = new PrismaClient()
const redis = new Redis(process.env.REDIS_URI)
export const authConfig = {
adapter: PrismaRedisAdapter(prisma, redis),
providers: [
// Your providers here
],
// Other NextAuth config...
})Page router
// pages/api/auth/[...nextauth].ts
import { authConfig } from '@libs/auth.ts' // Your auth config file
import NextAuth from 'next-auth'
export default NextAuth(authOptions)App router
// app/api/auth/[...nextauth]/route.ts
import { authConfig } from '@libs/auth.ts' // Your auth config file
import NextAuth from 'next-auth/next'
const handler = NextAuth(authOptions)
export { handler as GET, handler as POST }3. Environment Variables
# Database
DATABASE_URI="your-database-url"
# Redis
REDIS_URI="redis://localhost:6379"
# NextAuth
NEXTAUTH_SECRET="your-secret-key"
NEXTAUTH_URL="http://localhost:3000"Architecture
This adapter uses a hybrid approach:
- Prisma Database: Stores users, accounts, verification tokens, and authenticators
- Redis: Stores sessions with automatic expiration (TTL)
Why This Architecture?
- Performance: Redis provides fast session lookups and automatic cleanup
- Reliability: Critical user data is stored in your primary database
- Scalability: Redis can handle high-frequency session operations
- Cost Effective: Reduces database load for session management
API Reference
PrismaRedisAdapter(prisma, redis)
Creates a new adapter instance.
Parameters:
prisma: PrismaClient instance or extended clientredis: ioredis Redis instance
Returns: Auth.js Adapter
Session Storage
Sessions are stored in Redis with the following key pattern:
userSession:{sessionToken}Each session automatically expires based on the session's expires timestamp, ensuring automatic cleanup without manual intervention.
Configuration Examples
Basic Setup
// lib/auth.ts
import { PrismaRedisAdapter } from '@theiceji/authjs-prisma-redis-adapter'
import { PrismaClient } from '@prisma/client'
import Redis from 'ioredis'
const prisma = new PrismaClient()
const redis = new Redis()
export const authConfig = {
adapter: PrismaRedisAdapter(prisma, redis),
// ... other config
}With Custom Redis Configuration
const redis = new Redis({
host: 'localhost',
port: 6379,
password: 'your-password',
db: 0,
retryDelayOnFailover: 100,
maxRetriesPerRequest: 3,
})
export const authConfig = {
adapter: PrismaRedisAdapter(prisma, redis),
// ... other config
}With Prisma Extensions
const prisma = new PrismaClient().$extends({
// Your Prisma extensions
})
export const authConfig = {
adapter: PrismaRedisAdapter(prisma, redis),
// ... other config
}Deployment Considerations
Redis Configuration
For production, consider:
- Persistence: Configure Redis persistence (RDB/AOF) for session recovery
- Memory Management: Set appropriate
maxmemoryandmaxmemory-policy - Clustering: Use Redis Cluster for high availability
- Monitoring: Monitor Redis memory usage and connection count
Database Configuration
- Connection Pooling: Configure Prisma connection pooling
- Read Replicas: Use read replicas for better performance
- Backups: Ensure regular database backups
Troubleshooting
Common Issues
Session not found errors:
- Ensure Redis is running and accessible
- Check Redis connection configuration
- Verify session TTL settings
Database connection issues:
- Verify DATABASE_URI is correct
- Check Prisma schema matches your database
- Ensure database migrations are up to date
Type errors:
- Ensure all peer dependencies are installed
- Check TypeScript configuration
- Verify Prisma client generation
Development Setup
- Clone the repository
- Install dependencies:
bun install - Set up test database and Redis
- Run tests: Please see our Test Guide for details.
- Build:
bun run build
License
MIT License - see LICENSE for details.
Support
- Bug Reports: GitHub Issues
- Discussions: GitHub Discussions
- Documentation: Auth.js Documentation
Built with ❤️ by theiceji
