Skip to content

Commit

Permalink
doc: session special usage tip (#3304)
Browse files Browse the repository at this point in the history
  • Loading branch information
perzy authored and dead-horse committed Dec 13, 2018
1 parent 6f4e912 commit 9dc2037
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
13 changes: 13 additions & 0 deletions docs/source/en/core/cookie-and-session.md
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,19 @@ exports.deleteSession = function* (ctx) {
};
```

What you need to pay special attention to is that you need to avoid the following situations when setting session properties (which can cause field loss, See for details [koa-session source code](https://github.com/koajs/session/blob/master/lib/session.js#L37-L47)):

* do not startsWith `_`
* can not be `isNew`

```js
ctx.session._visited = 1; // × --> property will lost
ctx.session.isNew = 'HeHe'; // × --> session keyword, should not write it

// right way
ctx.session.visited = 1; // ✅ --> Everything is all right!
```

Session is built on top of Cookie.
By default, the content of Session is stored in a Cookie field as encrypted string.
Every time a client sends requests to server, the cookie is attached in requests.
Expand Down
14 changes: 14 additions & 0 deletions docs/source/zh-cn/core/cookie-and-session.md
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,20 @@ Session 的使用方法非常直观,直接读取它或者修改它就可以了
ctx.session = null;
```

需要 **特别注意** 的是:设置 session 属性时需要避免以下几种情况(会造成字段丢失,详见 [koa-session](https://github.com/koajs/session/blob/master/lib/session.js#L37-L47) 源码)


* 不要以 `_` 开头
* 不能为 `isNew`

```js
ctx.session._visited = 1; // × --> 该字段会在下一次请求时丢失
ctx.session.isNew = 'HeHe'; // × --> 为内部关键字, 不应该去更改

// 正确的用法
ctx.session.visited = 1; // ✅ --> Everything is all right!
```

Session 的实现是基于 Cookie 的,默认配置下,用户 Session 的内容加密后直接存储在 Cookie 中的一个字段中,用户每次请求我们网站的时候都会带上这个 Cookie,我们在服务端解密后使用。Session 的默认配置如下:

```js
Expand Down

0 comments on commit 9dc2037

Please sign in to comment.