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

@veloze/session

v0.2.1

Published

session store

Downloads

13

Readme

npm-badge actions-badge types-badge

@veloze/session

Session middleware for veloze. Works also with express

Comes packed with a

  • Cookie store as default (uses HS256 JWT)
  • Memory store (not for production)
  • Redis store (using ioredis)
  • SQL store (using sequelize)

Table of Contents

Usage

Installation

npm i @veloze/session

In your code:

import { Server, cookieParser } from 'veloze'
import { session } from '@veloze/session'
import { CookieStore } from '@veloze/session/CookieStore'

const app = new Server()

// using Cookie store
app.use(
  cookieParser,
  session({
    store: new CookieStore({
      // allows key rotation (1st secret is used for signing)
      secrets: [
        { kid: '2', secret: 's€cr3t'}, 
        { kid: '1', secret: 'older-s€cr3t'}
      ]
    }),
    // session cookie name
    name: 'session',
    // session expiry
    expires: '12 hours',
    // cookie options
    cookieOpts: { sameSite: 'Strict', httpOnly: true }
  }),
  async (req, res) => {
    // get session data
    const data = req.session
    // change or add properties
    data.username = 'alice'

    // set session data with an object
    req.session.set({ visits: 1, follows: ['bob'] })

    // explicitly save the session
    // session is also automatically saved before writing response headers
    await req.session.save()

    // reset session id, but maintain session data
    await req.session.resetId()

    // destroy the session
    await req.session.destroy()
  }
)

MemoryStore

Using Memory store

Note: Do not use in production.

See ./examples/memorystore.js

import { Server, send, queryParser, cookieParser, response } from 'veloze'
import { session, MemoryStore } from '@veloze/session'
import { view } from './view.js'

const store = new MemoryStore()

const app = new Server({ onlyHTTP1: true })

app.use(
  send,
  queryParser,
  cookieParser,
  // attach session middleware with store
  session({
    store,
    expires: 10,
    initialData: { visits: 0 }
  })
)

//...

RedisStore

Use Redis as session storage

Note: needs additional dependency

npm i ioredis

See ./examples/redisstore.js

import { Server, send, queryParser, cookieParser, response } from 'veloze'
import { session } from '@veloze/session'
import { view } from './view.js'

// import redis driver and store
import Redis from 'ioredis'
import { RedisStore } from '@veloze/session/RedisStore'

// create redis client
const client = new Redis({
  host: '127.0.0.1',
  port: 6379
  // username: '',
  // password: '',
  // db: 0,
  // keyPrefix: 'session:',
})
const store = new RedisStore({ client })

const app = new Server({ onlyHTTP1: true })

app.use(
  send,
  queryParser,
  cookieParser,
  // attach session middleware with store
  session({
    store,
    expires: 10,
    initialData: { visits: 0 }
  })
)

//...

MongoStore

Use MongoDB as session storage

Note: needs additional dependency

npm i mongodb

See ./examples/mongostore.js

import { Server, send, queryParser, cookieParser, response } from 'veloze'
import { session } from '@veloze/session'
import { view } from './view.js'

// import mongo driver and store
import { MongoClient } from 'mongodb'
import { MongoStore } from '@veloze/session/MongoStore'

// create mongo client
const client = new MongoClient('mongodb://root:example@localhost:27017')
const store = new MongoStore({ client })

const app = new Server({ onlyHTTP1: true })

app.use(
  send,
  queryParser,
  cookieParser,
  // attach session middleware with store
  session({
    store,
    expires: 10,
    // extendExpiry: true,
    initialData: { visits: 0 }
  })
)

//...

SqlStore

Use Sequelize to connect to your favorite SQL Database

Note: needs additional dependency

# for postgres
npm i pg
# for mariadb, mysql
npm i mysql2

See ./examples/postgresstore.js

import { Server, send, queryParser, cookieParser, response } from 'veloze'
import { session } from '@veloze/session'
import { view } from './view.js'

// import sequelize and store
import { Sequelize } from 'sequelize'
import { SqlStore } from '@veloze/session/SqlStore'

/**
 * Create database in PostgreSQL first
 * connect to "postgres" database and run:
 * ```sql
 * CREATE DATABASE test;
 * ```
 */

// creates postgres client
const client = new Sequelize({
  dialect: 'postgres', // don't forget to install "pg"
  host: 'localhost',
  port: 5432,
  username: 'root',
  password: 'example',
  database: 'test',
  logging: false
})
const store = new SqlStore({ client })
await store.init({ alter: true })

const app = new Server({ onlyHTTP1: true })

app.use(
  send,
  queryParser,
  cookieParser,
  // attach session middleware with store
  session({
    store,
    expires: 10,
    // extendExpiry: true,
    initialData: { visits: 0 }
  })
)

//...

API

Session Middleware

 function session(opts: {
    /** 
     * session store 
     * @default CookieStore
     */
    store?: import("./types").Store | undefined;
    /**
     * session expiration
     * @default '12 hours'
     */
    expires?: string | number | undefined;
    /**
     * session cookie name
     * @default 'session'
     */
    name?: string | undefined;
    /**
     * Cookie options
     */
    cookieOpts?: import("veloze/types/types.js").CookieOpts | undefined;
    /**
     * if `true` extend expiry on every request
     * @default false
     */
    extendExpiry?: boolean | undefined;
    /**
     * initial session data (if no session found)
     */
    initialData?: object;
    /**
     * signing secrets; 1st used to sign, all others to verify;
     * only required if using default CookieStore
     */
    secrets?: {
        kid: string;
        secret: string;
    }[] | undefined;
    randomId?: (() => string) | undefined;
}): Promise<(req, res, next) => void>;

Request Session Object

export interface ReqSession {
  /** set session data object */
  set(data: object): void
  /** extend the expiry time of the session */
  extendExpiry(): void
  /** renew the session Id */
  resetId(): Promise<void>
  /** explicitly save the session */
  save(): Promise<void>
  /** destroy the session */
  destroy(): Promise<void>
  /** set, get property on session object */
  [property: string]: any
}

License

MIT licensed