We'll need the koa-session, so install it using:
npm install --save koa-sessionWe will put the koa-session middleware in place. In this example, we'll use the our RAM to store sessions. Never use this in production environments. The session middleware handles all things for us, ie creating the session, setting the session cookie and creating the session object in context object.
Whenever we make a request from the same client again, we will have their session information stored with us(given that server was not restarted). We can add more properties to this session object. In the following example, we will create a view counter for a client.
var session = require('koa-session'); var koa = require('koa'); var app = koa(); app.keys = ['Shh, its a secret!']; app.use(session(app)); // Include the session middleware app.use(function *(){ var n = this.session.views || 0; this.session.views = ++n; if(n === 1) this.body = 'Welcome here for the first time!'; else this.body = "You've visited this page " + n + " times!"; }) app.listen(3000);What the above code does is, when a user visits the site, it creates a new session for the user and assigns them a cookie. Next time the user comes, the cooie is checked and the page_view session variable is updated accordingly.
Now if you run the app and go to localhost:3000, you'll get the response:
If you revisit the page, the page counter will increase. I refreshed the page 12 times in this case:
No comments:
Post a Comment