@rabithua/prisma-session-store
v1.0.0
Published
A modern Prisma-based session store for Express with TypeScript support and automatic cleanup
Maintainers
Readme
@rabithua/prisma-session-store
A modern, TypeScript-first session store for Express.js using Prisma ORM with automatic cleanup functionality.
Features
- 🚀 TypeScript Support: Full TypeScript support with comprehensive type definitions
- 🗄️ Multi-Database: Works with all Prisma-supported databases (PostgreSQL, MySQL, SQLite, MongoDB, etc.)
- 🧹 Auto Cleanup: Automatic cleanup of expired sessions with configurable intervals
- ⚡ Performance: Efficient database operations using Prisma's optimized queries
- 🔧 Configurable: Highly configurable with sensible defaults
- 🛡️ Error Handling: Robust error handling and graceful degradation
- 📦 Zero Dependencies: Only requires Prisma and Express-session as peer dependencies
Installation
npm install @rabithua/prisma-session-store
# or
yarn add @rabithua/prisma-session-store
# or
pnpm add @rabithua/prisma-session-store
# or
bun add @rabithua/prisma-session-storeDatabase Schema
First, add the Session model to your Prisma schema:
model Session {
id String @id @default(cuid())
sid String @unique
data String
expiresAt DateTime
@@map("sessions")
}Then run the migration:
npx prisma migrate dev
# or for MongoDB
npx prisma db pushBasic Usage
import express from 'express';
import session from 'express-session';
import { PrismaClient } from '@prisma/client';
import { PrismaSessionStore } from '@rabithua/prisma-session-store';
const app = express();
const prisma = new PrismaClient();
app.use(session({
store: new PrismaSessionStore({
prisma: prisma,
checkPeriod: 2 * 60 * 1000, // 2 minutes
}),
secret: 'your-secret-key',
resave: false,
saveUninitialized: false,
cookie: {
maxAge: 1000 * 60 * 60 * 24 * 7 // 1 week
}
}));
app.listen(3000);Configuration Options
interface PrismaSessionStoreOptions {
/**
* Prisma client instance (required)
*/
prisma: PrismaClient;
/**
* Cleanup check period in milliseconds
* @default 120000 (2 minutes)
*/
checkPeriod?: number;
/**
* Session table name (if using custom table name)
* @default 'session'
*/
tableName?: string;
/**
* Enable automatic cleanup of expired sessions
* @default true
*/
autoCleanup?: boolean;
/**
* Default session TTL in milliseconds
* @default 2678400000 (31 days)
*/
defaultTtl?: number;
}Advanced Usage
Custom Table Name
If you're using a different table name in your schema:
// In your schema.prisma
model UserSession {
id String @id @default(cuid())
sid String @unique
data String
expiresAt DateTime
@@map("user_sessions")
}
// In your application
const store = new PrismaSessionStore({
prisma: prisma,
tableName: 'userSession', // Use the model name, not the table name
});Manual Cleanup
const store = new PrismaSessionStore({
prisma: prisma,
autoCleanup: false, // Disable automatic cleanup
});
// Manual cleanup
const result = await store.cleanup();
console.log(`Cleaned up ${result.deletedCount} expired sessions`);Stop/Start Cleanup
const store = new PrismaSessionStore({ prisma });
// Stop automatic cleanup
store.stopCleanup();
// Restart automatic cleanup
store.startCleanup();API Reference
Methods
get(sid, callback)
Retrieve a session by session ID.
set(sid, session, callback)
Store or update a session.
destroy(sid, callback)
Destroy a session.
touch(sid, session, callback)
Update the expiration time of a session.
all(callback)
Retrieve all active sessions.
length(callback)
Get the count of active sessions.
clear(callback)
Clear all sessions.
cleanup()
Manually cleanup expired sessions. Returns a promise with the number of deleted sessions.
startCleanup()
Start automatic cleanup of expired sessions.
stopCleanup()
Stop automatic cleanup.
Error Handling
The store handles various error conditions gracefully:
- Database connection errors: Passed to Express session callbacks
- Invalid session data: Corrupted sessions are ignored during retrieval
- Missing sessions: Handled as null/undefined sessions
- Cleanup errors: Logged but don't interrupt application flow
Database Support
This session store works with all databases supported by Prisma:
- PostgreSQL
- MySQL
- SQLite
- MongoDB
- SQL Server
- CockroachDB
Performance Considerations
- The store uses efficient Prisma queries with proper indexing
- Automatic cleanup runs in the background without blocking operations
- The
sidfield is indexed for fast lookups - JSON serialization/deserialization is optimized for performance
Migration from @quixo3/prisma-session-store
This package is designed as a drop-in replacement for @quixo3/prisma-session-store with additional features:
// Before
import { PrismaSessionStore } from '@quixo3/prisma-session-store';
// After
import { PrismaSessionStore } from '@rabithua/prisma-session-store';
// The API is compatible, just pass the prisma instance
const store = new PrismaSessionStore({
prisma: prismaClient,
checkPeriod: 2 * 60 * 1000,
});Contributing
We welcome contributions! Please see our Contributing Guide for details.
License
MIT License - see the LICENSE file for details.
Support
Made with ❤️ by rabithua
