Secbone / koa-session2

Middleware for Koa2 to get/set session
MIT License
153 stars 30 forks source link
koa2 nodejs

koa-session2

NPM version Build Status Downloads Test coverage

Middleware for Koa2 to get/set session use with custom stores such as Redis or mongodb

Use native ES6(async/await) by Nodejs v7.6.0 +

Or you can use the old versions:

Require

node v7.6 +

Install

npm install koa-session2

Usage

const Koa = require("koa");
const session = require("koa-session2");

const app = new Koa();

app.use(session({
    key: "SESSIONID",   //default "koa:sess"
}));

Custom Stores

Store.js

const Redis = require("ioredis");
const { Store } = require("koa-session2");

class RedisStore extends Store {
    constructor() {
        super();
        this.redis = new Redis();
    }

    async get(sid, ctx) {
        let data = await this.redis.get(`SESSION:${sid}`);
        return JSON.parse(data);
    }

    async set(session, { sid =  this.getID(24), maxAge = 1000000 } = {}, ctx) {
        try {
            // Use redis set EX to automatically drop expired sessions
            await this.redis.set(`SESSION:${sid}`, JSON.stringify(session), 'EX', maxAge / 1000);
        } catch (e) {}
        return sid;
    }

    async destroy(sid, ctx) {
        return await this.redis.del(`SESSION:${sid}`);
    }
}

module.exports = RedisStore;

main.js

const Koa = require("koa");
const session = require("koa-session2");
const Store = require("./Store.js");

const app = new Koa();

app.use(session({
    store: new Store()
}));

app.use(ctx => {
    let user = ctx.session.user;

    ctx.session.view = "index";
});

app.use(ctx => {
    // refresh session if set maxAge
    ctx.session.refresh()
})

Options

Most options based on cookies

Methods

License

MIT