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 🙏

© 2024 – Pkg Stats / Ryan Hefner

session-store-js

v1.0.1

Published

This package provides a robust and flexible session management solution for Express.js applications. It supports two types of session storage: MemoryStore for in-memory storage and FileStore for file system persistence.

Downloads

16

Readme

Session-Store-Js

This package provides a robust and flexible session management solution for Express.js applications. It supports two types of session storage: MemoryStore for in-memory storage and FileStore for file system persistence.

Installation

To install PryxAPI, run the following command in your project directory:

npm install session-store-js

Key Features

  • Dual Storage Support: Choose between MemoryStore for quick, non-persistent sessions, or FileStore for persistent sessions.
  • Express.js Integration: Seamlessly integrates as Express middleware.
  • Asynchronous API: All session operations are asynchronous for improved performance.
  • Automatic Cookie Management: Handles session cookies with security in mind.
  • Comprehensive Session Operations: Includes methods for getting, setting, destroying, and touching sessions.
  • Session Overview: Provides methods to retrieve all active sessions and clear them globally.
  • Advanced Store Management: Includes methods to control cleanup and maintenance processes for both MemoryStore and FileStore.

Usage

To use the SessionManager, first import it and create an instance::

const SessionManager = require('session-store-js');

const sessionManager = new SessionManager({
    storeType: 'memory', // or 'file'
    storeOptions: {}, // options specific to the store type
    secret: 'your-secret-key',
    cookieName: 'custom.sid',
    maxAge: 3600000 // 1 hour
});

Configuration Options

  • storeType: Choose 'memory' or 'file'.

  • storeOptions: Configuration for the chosen store type.

    • MemoryStore options:

      • maxAge: Maximum session age (milliseconds).
      • cleanupInterval: Interval for clearing expired sessions (milliseconds).
      • indexInterval: Interval for rebuilding the expiration index (milliseconds).
    • FileStore options:

      • path: Directory for storing session files.
      • ttl: Session time-to-live (seconds).
  • secret: Secret key for signing cookies.

  • cookieName: Custom name for the session cookie.

  • maxAge: Session lifetime (milliseconds).

Express Middleware

Apply the session middleware to your Express app:

app.use(sessionManager.middleware());

Common Session Operations

  1. Get a Session Value
const value = await sessionManager.get(req, 'key');
  1. Set a Session Value
await sessionManager.set(req, 'key', 'value');
  1. Destroy a Session
await sessionManager.destroy(req);
  1. Update Session Expiration (Touch)
await sessionManager.touch(req);
  1. Retrieve All Sessions
const sessions = await sessionManager.getAllSessions();
  1. Clear All Sessions
await sessionManager.clearAllSessions();

MemoryStore Specific Operations

  1. Start Cleanup Process
sessionManager.store.startCleanup();
  1. Stop Cleanup Process
sessionManager.store.stopCleanup();
  1. Start Index Rebuild Process
sessionManager.store.startIndexRebuild();
  1. Stop Index Rebuild Process
sessionManager.store.stopIndexRebuild();

FileStore Specific Operations

  1. Ensure Directory Exists
const filePath = sessionManager.store._getFilePath(sessionId);
  1. Get File Path for Session
sessionManager.store.stopCleanup();

Examples

MemoryStore Example

const express = require('express');
const cookieParser = require('cookie-parser');
const SessionManager = require('session-store-js');

const app = express();
app.use(cookieParser());

const sessionManager = new SessionManager({
    storeType: 'memory',
    storeOptions: {
        cleanupInterval: 300000, // 5 minutes
        indexInterval: 60000 // 1 minute
    },
    secret: 'your-secret-key',
    cookieName: 'my.session.id',
    maxAge: 3600000 // 1 hour
});

app.use(sessionManager.middleware());

app.get('/', async (req, res) => {
    const visitCount = (await sessionManager.get(req, 'visits') || 0) + 1;
    await sessionManager.set(req, 'visits', visitCount);
    res.send(`Welcome! You've visited this page ${visitCount} times.`);
});

app.get('/touch', async (req, res) => {
    await sessionManager.touch(req);
    res.send('Session touched');
});

app.get('/logout', async (req, res) => {
    await sessionManager.destroy(req);
    res.send('Logged out successfully');
});

app.get('/all-sessions', async (req, res) => {
    const sessions = await sessionManager.getAllSessions();
    res.json(sessions);
});

app.get('/clear-all', async (req, res) => {
    await sessionManager.clearAllSessions();
    res.send('All sessions cleared');
});

app.get('/start-cleanup', (req, res) => {
    sessionManager.store.startCleanup();
    res.send('Cleanup started');
});

app.get('/stop-cleanup', (req, res) => {
    sessionManager.store.stopCleanup();
    res.send('Cleanup stopped');
});

app.get('/start-index-rebuild', (req, res) => {
    sessionManager.store.startIndexRebuild();
    res.send('Index rebuild started');
});

app.get('/stop-index-rebuild', (req, res) => {
    sessionManager.store.stopIndexRebuild();
    res.send('Index rebuild stopped');
});

app.listen(3000, () => console.log('MemoryStore server running on port 3000'));

FileStore Example

const express = require('express');
const cookieParser = require('cookie-parser');
const SessionManager = require('session-store-js');

const app = express();
app.use(cookieParser());

const sessionManager = new SessionManager({
    storeType: 'file',
    storeOptions: {
        path: './sessions',
        ttl: 86400, // 1 day in seconds
    },
    secret: 'your-file-secret-key',
    cookieName: 'my.file.session.id',
    maxAge: 86400000 // 1 day in milliseconds
});

app.use(sessionManager.middleware());

app.get('/', async (req, res) => {
    const visitCount = (await sessionManager.get(req, 'visits') || 0) + 1;
    await sessionManager.set(req, 'visits', visitCount);
    res.send(`Welcome! You've visited this page ${visitCount} times.`);
});

app.get('/touch', async (req, res) => {
    await sessionManager.touch(req);
    res.send('Session touched');
});

app.get('/logout', async (req, res) => {
    await sessionManager.destroy(req);
    res.send('Logged out successfully');
});

app.get('/all-sessions', async (req, res) => {
    const sessions = await sessionManager.getAllSessions();
    res.json(sessions);
});

app.get('/clear-all', async (req, res) => {
    await sessionManager.clearAllSessions();
    res.send('All sessions cleared');
});

app.get('/ensure-directory', async (req, res) => {
    await sessionManager.store.ensureDirectory();
    res.send('Session directory ensured');
});

app.get('/file-path', (req, res) => {
    if (req.sessionID) {
        const filePath = sessionManager.store._getFilePath(req.sessionID);
        res.send(`Session file path: ${filePath}`);
    } else {
        res.status(400).send('No active session');
    }
});

app.listen(3001, () => console.log('FileStore server running on port 3001'));

Explanation of Examples

MemoryStore Example

  • Initializes SessionManager with MemoryStore and specific options.
  • Implements a visit counter using session storage.
  • Includes routes to start and stop the cleanup process.

FileStore Example

  • Configures SessionManager with FileStore and appropriate options.
  • Implements the same visit counter functionality.
  • Includes a route to ensure the session directory exists.

Both examples demonstrate the consistent API across different storage types, while also showcasing store-specific operations.

Best Practices

  1. Use a strong, unique secret for production environments.
  2. Adjust maxAge and cleanup intervals based on your application's needs and traffic patterns.
  3. For FileStore, ensure the specified path is secure and has appropriate permissions.
  4. Regularly monitor and manage session cleanup processes to optimize performance.

Security Considerations

  • The middleware automatically sets secure and httpOnly flags on cookies in production mode.
  • Regularly rotate the secret key to enhance security.
  • Be cautious when using getAllSessions() in production, as it can be resource-intensive for large numbers of sessions.
  • Ensure that routes controlling store-specific operations are properly secured in production environments.
  • For FileStore, implement proper file system permissions and consider encryption for sensitive session data.

This comprehensive guide covers the usage of your SessionManager package with both MemoryStore and FileStore, including common operations and store-specific functionalities. It provides developers with the necessary information to effectively implement and manage sessions in their Express.js applications using your package.