• Stars
    star
    414
  • Rank 104,550 (Top 3 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 11 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

koa session store with memory, redis or others.

generic-session

NPM version build status Coveralls David deps node version npm download Gittip

Generic session middleware for koa, easy use with custom stores such as redis or mongo, supports defer session getter.

This middleware will only set a cookie when a session is manually set. Each time the session is modified (and only when the session is modified), it will reset the cookie and session.

You can use the rolling sessions that will reset the cookie and session for every request which touch the session. Save behavior can be overridden per request.

For async/await and Node v6.9.0+ support use v2.x of this package, for older use v1.x

Usage

Example

var session = require('koa-generic-session');
var redisStore = require('koa-redis');
var koa = require('koa');

var app = new koa(); // for koa v1 use `var app = koa();`
app.keys = ['keys', 'keykeys'];
app.use(session({
  store: redisStore()
}));

app.use(function *() {
  switch (this.path) {
  case '/get':
    get.call(this);
    break;
  case '/remove':
    remove.call(this);
    break;
  case '/regenerate':
    yield regenerate.call(this);
    break;
  }
});

function get() {
  var session = this.session;
  session.count = session.count || 0;
  session.count++;
  this.body = session.count;
}

function remove() {
  this.session = null;
  this.body = 0;
}

function *regenerate() {
  get.call(this);
  yield this.regenerateSession();
  get.call(this);
}

app.listen(8080);
  • After adding session middleware, you can use this.session to set or get the sessions.
  • Getting session ID via this.sessionId.
  • Setting this.session = null; will destroy this session.
  • Altering this.session.cookie changes the cookie options of this user. Also you can use the cookie options in session the store. Use for example cookie.maxAge as the session store's ttl.
  • Calling this.regenerateSession will destroy any existing session and generate a new, empty one in its place. The new session will have a different ID.
  • Calling this.saveSession will save an existing session (this method was added for koa-redirect-loop)
  • Setting this.sessionSave = true will force saving the session regardless of any other options or conditions.
  • Setting this.sessionSave = false will prevent saving the session regardless of any other options or conditions.

Options

  • key: cookie name defaulting to koa.sid.

  • prefix: session prefix for store, defaulting to koa:sess:.

  • ttl: ttl is for sessionStore's expiration time (not to be confused with cookie expiration which is controlled by cookie.maxAge), can be a number or a function that returns a number (for dynamic TTL), default to null (means get ttl from cookie.maxAge or cookie.expires).

  • rolling: rolling session, always reset the cookie and sessions, defaults to false.

  • genSid: default sid was generated by uid2, you can pass a function to replace it (supports promises/async functions).

  • defer: defers get session, only generate a session when you use it through var session = yield this.session;, defaults to false.

  • allowEmpty: allow generation of empty sessions.

  • errorHandler(err, type, ctx): Store.get and Store.set will throw in some situation, use errorHandle to handle these errors by yourself. Default will throw.

  • reconnectTimeout: When store is disconnected, don't throw store unavailable error immediately, wait reconnectTimeout to reconnect, default is 10s.

  • sessionIdStore: object with get, set, reset methods for passing session id throw requests.

  • valid: valid(ctx, session), valid session value before use it.

  • beforeSave: beforeSave(ctx, session), hook before save session.

  • store: session store instance. It can be any Object that has the methods set, get, destroy like MemoryStore.

  • cookie: session cookie settings, defaulting to:

    {
      path: '/',
      httpOnly: true,
      maxAge: 24 * 60 * 60 * 1000 //one day in ms,
      overwrite: true,
      signed: true
    }

    For a full list of cookie options see expressjs/cookies.

    if you setcookie.maxAge to null, meaning no "expires" parameter is set so the cookie becomes a browser-session cookie. When the user closes the browser the cookie (and session) will be removed.

    Notice that ttl is different from cookie.maxAge, ttl set the expire time of sessionStore. So if you set cookie.maxAge = null, and ttl=ms('1d'), the session will expired after one day, but the cookie will destroy when the user closes the browser. And mostly you can just ignore options.ttl, koa-generic-session will parse cookie.maxAge as the tll.

    If your application requires dynamic expiration, control cookie.maxAge using ctx.session.cookie.maxAge = dynamicMaxAge, when you need ttl to differ from cookie.maxAge (a common example is browser-session cookies having cookie.maxAge = null, but you want them to not live indefinitely in the store) specify a function for ttl:

    {
      ttl: (session) => {
        // Expire browser-session cookies from the store after 1 day
        if (session.cookie?.maxAge === null) {
          return 1000 * 60 * 60 * 24;
        }
      }
    }

Hooks

  • valid(): valid session value before use it
  • beforeSave(): hook before save session

Session Store

You can use any other store to replace the default MemoryStore, it just needs to follow this api:

  • get(sid): get session object by sid
  • set(sid, sess, ttl): set session object for sid, with a ttl (in ms)
  • destroy(sid): destroy session for sid

the api needs to return a Promise, Thunk or generator.

And use these events to report the store's status.

  • connect
  • disconnect

Stores Presented

Graceful shutdown

Since this middleware comes with an auto-reconnect feature, it's very likely you can't gracefully shutdown after closing the client as generic-session will try to recover the connection, in those cases you can disable reconnect feature (

store.on('disconnect', () => {
if (storeStatus !== 'available') return
storeStatus = 'pending'
waitStore = new Promise((resolve, reject) => {
setTimeout(() => {
if (storeStatus === 'pending') storeStatus = 'unavailable'
reject(new Error('session store is unavailable'))
}, reconnectTimeout)
store.once('connect', resolve)
})
) desactivating the client emitter (do this only when stopping the server)

Example with ioredis

  // ...disconnecting from db
  redisClient.emit = () => true;
  await redisClient.quit();
  // ...stopping the server

Licences

(The MIT License)

Copyright (c) 2013 - 2016 dead-horse and other contributors

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

More Repositories

1

koa

Expressive middleware for node.js using ES2017 async functions
JavaScript
34,326
star
2

examples

Example Koa apps
JavaScript
4,471
star
3

jwt

Koa middleware for validating JSON Web Tokens
JavaScript
1,333
star
4

bodyparser

Koa body parsing middleware
TypeScript
1,273
star
5

static

Static file server middleware
JavaScript
1,124
star
6

compose

Middleware composition utility
JavaScript
986
star
7

koa-body

koa body parser middleware
TypeScript
923
star
8

session

Simple session middleware for koa
JavaScript
902
star
9

router

Router middleware for Koa. Maintained by @forwardemail and @ladjs.
JavaScript
790
star
10

cors

Cross-Origin Resource Sharing(CORS) for koa
JavaScript
723
star
11

kick-off-koa

[MAINTAINERS WANTED] An intro to koa via a set of self-guided workshops
JavaScript
693
star
12

logger

Development style logging middleware
JavaScript
561
star
13

mount

Mount other Koa applications or middleware to a given pathname
JavaScript
549
star
14

ratelimit

Rate limiter middleware
JavaScript
466
star
15

joi-router

Configurable, input and output validated routing for koa
JavaScript
450
star
16

route

Simple route middleware
JavaScript
442
star
17

workshop

Koa Training Workshop
JavaScript
436
star
18

compress

Compress middleware for koa
JavaScript
432
star
19

koa.io

[MAINTAINERS WANTED] Realtime web framework combine koa and socket.io.
JavaScript
427
star
20

send

Transfer static files
TypeScript
420
star
21

koa-redis

Redis storage for Koa session middleware/cache with Sentinel and Cluster support
JavaScript
352
star
22

koala

[SEEKING MAINTAINER] An HTTP/2 and ES6 Module-ready Koa Suite
JavaScript
320
star
23

static-cache

[MAINTAINERS WANTED] Static cache for koa
JavaScript
293
star
24

csrf

CSRF tokens for koa
JavaScript
265
star
25

react-view

A Koa view engine which renders React components on server
JavaScript
256
star
26

convert

Convert koa generator-based middleware to promise-based middleware
JavaScript
254
star
27

ejs

a koa view render middleware, support all feature of ejs
JavaScript
248
star
28

json

pretty-printed JSON response middleware
JavaScript
197
star
29

todo

a todo example write with koa and react
JavaScript
165
star
30

koa-hbs

Handlebars templates for Koa.js
JavaScript
159
star
31

cash

HTTP response caching for Koa. Supports Redis, in-memory store, and more!
JavaScript
154
star
32

onerror

an error handler for koa, hack ctx.onerror
JavaScript
139
star
33

basic-auth

blanket basic auth middleware
JavaScript
138
star
34

userauth

koa user auth middleware
JavaScript
137
star
35

multer

Middleware for handling `multipart/form-data` for koa, based on Express's multer.
JavaScript
137
star
36

response-time

X-Response-Time middleware
JavaScript
124
star
37

trie-router

Trie-routing for Koa
JavaScript
122
star
38

koa-roles

koa version of Connect-Roles
JavaScript
117
star
39

etag

ETag support for Koa responses
JavaScript
112
star
40

bunyan-logger

Koa middleware for bunyan request logging
JavaScript
108
star
41

favicon

Koa middleware for serving a favicon
JavaScript
104
star
42

error

Error response middleware (text, json, html)
JavaScript
103
star
43

rewrite

URL rewriting middleware
JavaScript
100
star
44

json-filter

Middleware allowing the client to filter the response to only what they need, reducing the amount of traffic over the wire.
JavaScript
92
star
45

json-error

Error handler for pure-JSON apps
JavaScript
89
star
46

qs

qs for koa, and use querystring more safely.
JavaScript
85
star
47

bigpipe-example

[DEPRECATED] BigPipe using koa and component
JavaScript
83
star
48

common

[DEPRECATED] USE INDIVIDUAL MODULES
JavaScript
77
star
49

locales

koa locales, i18n solution for koa
JavaScript
67
star
50

koa-lusca

koa version of lusca. Application security for koa.
JavaScript
65
star
51

cluster

Koa clustering and error handling utility
JavaScript
64
star
52

parameter

parameter validate middleware for koa, powered by parameter
JavaScript
62
star
53

conditional-get

Conditional GET middleware for koa
JavaScript
59
star
54

trace

generic tracing for koa
JavaScript
53
star
55

koa-range

[MAINTAINERS WANTED] range request implementation for koa, see http://tools.ietf.org/html/rfc7233
JavaScript
47
star
56

sendfile

basic file-sending utility for koa
JavaScript
45
star
57

koajs.com

The koajs.com website
HTML
42
star
58

mock

Simple web page mock middleware
JavaScript
40
star
59

body-parsers

collection of koa body parsers
JavaScript
37
star
60

koa-markdown

Auto convert markdown to html for koa. Inspired by connect-markdown
JavaScript
37
star
61

koa-gzip

[Deprecated] please use koa-compress instead
JavaScript
36
star
62

file-server

file serving middleware for koa
JavaScript
36
star
63

bundle

Generic asset pipeline with caching, etags, minification, gzipping and sourcemaps.
JavaScript
36
star
64

resourcer

A simple resource directory mounter for koa.
JavaScript
34
star
65

path-match

koa route middleware
JavaScript
33
star
66

html-minifier

minify HTML responses like some crazy guy
JavaScript
31
star
67

webcam-mjpeg-stream

[DEPRECATED] Stream JPEG snapshots from your Mac
JavaScript
28
star
68

timer

time your middleware
JavaScript
26
star
69

statsd

Statsd middleware
JavaScript
24
star
70

redis-session-sets

Koa Redis sessions with field-referencing cross sets
JavaScript
20
star
71

accesslog

Middleware for common log format access logs
JavaScript
19
star
72

is-json

check if a koa body should be interpreted as JSON
JavaScript
17
star
73

charset

use iconv-lite to encode the body and set charset to content-type
JavaScript
16
star
74

koa-safe-jsonp

Safe jsonp plusins for koa.
JavaScript
16
star
75

trace-influxdb

InfluxDB tracing for koa-trace
JavaScript
15
star
76

stateless-csrf

CSRF without sessions.
JavaScript
15
star
77

atomic-session

DEPRECATED
JavaScript
15
star
78

cross-cookies

Easily set cookies across subdomains
JavaScript
13
star
79

koa-github

simple github auth middleware for koa
JavaScript
13
star
80

s3-cache

Koa middleware to cache and serve from S3
JavaScript
11
star
81

eslint-config-koa

Koa's ESLint config, based on Standard
JavaScript
11
star
82

ctx-cache-control

Augment Koa with ctx.cacheControl(maxAge)
JavaScript
9
star
83

snapshot

take snapshot when request, cache by request path.
JavaScript
9
star
84

compressor

[DEPRECATED] Compress middleware for koa that always compresses
JavaScript
9
star
85

koa-fresh

DEPRECATED
JavaScript
8
star
86

cdn

[DEPRECATED] middleware for a koa-based CDN
JavaScript
7
star
87

koa-rt

koa rt with microtime
JavaScript
6
star
88

override-method

method override utility for koa
JavaScript
6
star
89

ctx-basic-auth

Augments Koa with ctx.basicAuth
JavaScript
5
star
90

resourcer-docs

[MAINTAINERS WANTED] Simple app that generates documentation for routes mounted using koa-resourcer.
JavaScript
5
star
91

middleware-hook

low-level hooks for your middleware
JavaScript
5
star
92

path

[DEPRECATED] path-matching middleware for koa
JavaScript
4
star
93

observable-redis-session

[DEPRECATED] Observable, atomic sessions for Koa using Redis
JavaScript
2
star
94

help

koa(1) executable for instant help
2
star
95

discussions

KoaJS Discussions
1
star