nuxt-session
Nuxt session middleware to persist data across multiple requests, supports many backends via unjs/unstorage: memory, redis, fs, ...
Features
- ✔️ Persistent sessions across requests
- ✔️ Storage via unjs/unstorage - use memory, redis, fs, cloudflare-kv, ... to store your session data
- ✔️ Configurable session duration
- ✔️ Automatic session storage cleanup on expiry
- ✔️ Transport method: Cookies
Use the module-playground (see playground below) to play around with the module.
Usage
- Install the package:
npm i @sidebase/nuxt-session
- Add the package to your
nuxt.config.ts
:
export default defineNuxtConfig({
modules: ['@sidebase/nuxt-session'],
})
- Each request will now have a session at
event.context.session
that looks like:
{
id: 'TLyEy2Mav2G_sawgek7fqqj6EaWrO9LDAfLjhjHRKbE6M-_nGhT1iK7sTwqZ-xoT',
createdAt: '2022-10-12T09:12:38.406Z'
}
All modifications of ``event.context.session` will automatically be stored. Here's an endpoint that persists a counter per user:
export default defineEventHandler(async (event: CompatibilityEvent) => {
const currentCount = event.context.session.count || 0
event.context.session.count = currentCount + 1
return event.context.session.count
})
To use the session on the client side (i.e., in your client app) you could create an endpoint that returns the session (or a part of it):
export default defineEventHandler((event: CompatibilityEvent) => event.context.session)
Playground
An example page making use of nuxt-session
:
See the playground to interactively use this:
> git clone https://github.com/sidebase/nuxt-session
> cd nuxt-session
> npm i
> npm run dev:prepare
> npm run dev
Development
- Run
npm run dev:prepare
to generate type stubs. - Use
npm run dev
to start playground in development mode. - Run
npm run lint
to run eslint - Run
npm run type
to run typescheck via tsc