@tinyhttp/sessiondeprecated

Session middleware for tinyhttp

Usage no npm install needed!

<script type="module">
  import tinyhttpSession from 'https://cdn.skypack.dev/@tinyhttp/session';
</script>

README

@tinyhttp/session

npm (scoped) npm

Session middleware for tinyhttp. A rewrite of micro-session.

Install

pnpm i @tinyhttp/session

API

import { SessionManager, MemoryStore } from '@tinyhttp/session'

SessionManager

Creates a getSession async function to get session data from req and res and save them to store. Only secret option is required, all of the rest are optional. Inherits all options from SessionOptions.

Options

See express-session session(options).

MemoryStore

Simple in-memory store that implements ExpressStore (from express-session types). Not intended to use in production.

const store = new MemoryStore()

store.clear(cb)

Clear all sessions.

store.destroy(id, cb)

Destroy a session by the given ID.

store.get(id, cb)

Fetch session by the given session ID.

store.set(id, session, cb)

Commit the given session associated with the given sessionId to the store.

length(cb)

Get number of active sessions.

touch(id, session, cb)

Touch the given session object associated with the given session ID.

Example

import { App } from '@tinyhttp/app'
import { SessionManager, MemoryStore } from '@tinyhttp/session'

const app = new App()

const store = new MemoryStore()
const getSession = SessionManager({
  store,
  secret: 'test'
})

app
  .use(async (req, res) => {
    // Get session data from req and res
    const session = await getSession(req, res)

    // Increment on every request and keep in memory
    if (!session.test) session.test = 1
    else session.test += 1

    res.json({ t: session.test })
  })
  .listen(3000)

Alternatives