Simple session middleware for Koa. Defaults to cookie-based sessions and supports external stores.
Requires Node 7.6 or greater for async/await support
$ npm install koa-session
6.x changed the default cookie key from koa:sess
to koa.sess
to ensure set-cookie
value valid with HTTP spec.see issue. If you want to be compatible with the previous version, you can manually set config.key
to koa:sess
.
View counter example:
const session = require('koa-session');
const Koa = require('koa');
const app = new Koa();
app.keys = ['some secret hurr'];
const CONFIG = {
key: 'koa.sess', /** (string) cookie key (default is koa.sess) */
/** (number || 'session') maxAge in ms (default is 1 days) */
/** 'session' will result in a cookie that expires when session/browser is closed */
/** Warning: If a session cookie is stolen, this cookie will never expire */
maxAge: 86400000,
autoCommit: true, /** (boolean) automatically commit headers (default true) */
overwrite: true, /** (boolean) can overwrite or not (default true) */
httpOnly: true, /** (boolean) httpOnly or not (default true) */
signed: true, /** (boolean) signed or not (default true) */
rolling: false, /** (boolean) Force a session identifier cookie to be set on every response. The expiration is reset to the original maxAge, resetting the expiration countdown. (default is false) */
renew: false, /** (boolean) renew session when session is nearly expired, so we can always keep user logged in. (default is false)*/
secure: true, /** (boolean) secure cookie*/
sameSite: null, /** (string) session cookie sameSite options (default null, don't set it) */
};
app.use(session(CONFIG, app));
// or if you prefer all default config, just use => app.use(session(app));
app.use(ctx => {
// ignore favicon
if (ctx.path === '/favicon.ico') return;
let n = ctx.session.views || 0;
ctx.session.views = ++n;
ctx.body = n + ' views';
});
app.listen(3000);
console.log('listening on port 3000');
The cookie name is controlled by the key
option, which defaultsto "koa.sess". All other options are passed to ctx.cookies.get()
andctx.cookies.set()
allowing you to control security, domain, path,and signing among other settings.
encode/decode
SupportUse options.encode
and options.decode
to customize your own encode/decode methods.
valid()
: valid session value before use itbeforeSave()
: hook before save sessionThe session is stored in a cookie by default, but it has some disadvantages:
You can store the session content in external stores (Redis, MongoDB or other DBs) by passing options.store
with three methods (these need to be async functions):
get(key, maxAge, { rolling, ctx })
: get session object by keyset(key, sess, maxAge, { rolling, changed, ctx })
: set session object for key, with a maxAge
(in ms)destroy(key, {ctx})
: destroy session for keyOnce you pass options.store
, session storage is dependent on your external store -- you can't access the session if your external store is down. Use external session stores only if necessary, avoid using session as a cache, keep the session lean, and store it in a cookie if possible!
The way of generating external session id is controlled by the options.genid(ctx)
, which defaults to uuid.v4()
.
If you want to add prefix for all external session id, you can use options.prefix
, it will not work if options.genid(ctx)
present.
If your session store requires data or utilities from context, opts.ContextStore
is also supported. ContextStore
must be a class which claims three instance methods demonstrated above. new ContextStore(ctx)
will be executed on every request.
koa-session
will emit event on app
when session expired or invalid:
session:missed
: can't get session value from external store.session:invalid
: session value is invalid.session:expired
: session value is expired.External key is used the cookie by default, but you can use options.externalKey
to customize your own external key methods. options.externalKey
with two methods:
get(ctx)
: get the external keyset(ctx, value)
: set the external keyReturns true if the session is new.
if (this.session.isNew) {
// user has not logged in
} else {
// user has already logged in
}
Get cookie's maxAge.
Set cookie's maxAge.
Get session external key, only exist when external session store present.
Save this session no matter whether it is populated.
Session headers are auto committed by default. Use this if autoCommit
is set to false
.
To destroy a session simply set it to null
:
this.session = null;
MIT
一、术语session session:中文经常翻译为 ‘会话’,其本来的含义是指有始有终的一系列动作/消息,比如:打电话时从拿起电话拨号到挂断电话这中间的一系列过程可以称为一个session。在阅读技术书籍时我们可能会看到这样的话“在一个浏览器会话期间…”,这里的会话一词用的就是其本义,是指从一个浏览器窗口从打开到关闭的这一整个期间①。最混乱的是“用户(客户端)在一次会话期间”这样一句话,他
写在前面 Session简介 是什么? Session在网络中表示“会话控制”,用于存储特定用户所需的属性和其他的配置信息;Session表示一个特定的时间间隔,可以指用户从登陆系统到注销退出系统之家的时间。 为什么出现? 因为http 是一种无状态协议,如果没有Session的话,服务器无法识别请求是否来自同一个用户!在一些业务场景中需要知道前面的操作和后台的操作是不是同一个用户的行为,即业务之
转自:http://www.cnblogs.com/lenther2002/p/4822325.html 区别: Asp.Net中的Session与Cookie最大的区别在于:Cookie信息全部存放于客户端,Session则只是将一个ID存放在客户端做为与服务端验证的标记,而真正的数据都是放在服务端的内存之中的。 在传统web编程语言(比如asp)中,session的过期完全是按照TimeO
前言 需求:如何保证同一个账号保证只有一个在线。(即:我在设备A上先登录账号guest,同时另外一个人在设备B上也登陆账号guest,此时,设备A上的账号将会被挤下线) 思路 账号登录成功后,在数据库或redis中查询当前用户绑定的sessionId 如果有值,则调用SessionRepository 删除当前session 在数据库或redis 记录当前登录账号对应的新的sessionId 步骤
Session其实分为客户端Session和服务器端Session。 当用户首次与Web服务器建立连接的时候,服务器会给用户分发一个 SessionID作为标识。SessionID是一个由24个字符组成的随机字符串。用户每次提交页面,浏览器都会把这个SessionID包含在 HTTP头中提交给Web服务器,这样Web服务器就能区分当前请求页面的是哪一个客户端。 这个SessionID就是保存在客户
引言——上文讲的是cookie,但是cookie的键和值都是明文的形式存储在客户端浏览器上,很不安全! 那有没有更好些的来存储登录状态的方式呢??? 这就需要讲讲session了! 1.状态保持——cookie和session: http协议是无状态的:每次请求都是一次新的的请求,不会记得之前通信的状态。 客户端与服务端的一次通信,就是一次会话实现状态保持的方式:在客户端或服务端存储与会话有关的数
前言 本文主要介绍Session的基本知识及基本使用方法 一、Session是什么? 服务器为了保存用户状态而创建的一个特殊的对象。 当浏览器第一次访问服务器时,服务器创建一个session对象(该对象有一个唯一的id,一般称之为sessionId),服务器会将sessionId以cookie的方式发送给浏览器。 当浏览器再次访问服务器时,会将sessionId发送过来,服务器依据sessionI