npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@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.

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-adapter

Peer Dependencies

Make sure you have the required peer dependencies installed:

npm install @auth/core @prisma/client ioredis

Quick 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?

  1. Performance: Redis provides fast session lookups and automatic cleanup
  2. Reliability: Critical user data is stored in your primary database
  3. Scalability: Redis can handle high-frequency session operations
  4. Cost Effective: Reduces database load for session management

API Reference

PrismaRedisAdapter(prisma, redis)

Creates a new adapter instance.

Parameters:

  • prisma: PrismaClient instance or extended client
  • redis: 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 maxmemory and maxmemory-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

  1. Clone the repository
  2. Install dependencies: bun install
  3. Set up test database and Redis
  4. Run tests: Please see our Test Guide for details.
  5. Build: bun run build

License

MIT License - see LICENSE for details.

Support


Built with ❤️ by theiceji