- Koa.js - Resources
- Koa.js - Scaffolding
- Koa.js - Logging
- Koa.js - RESTful APIs
- Koa.js - Database
- Koa.js - Caching
- Koa.js - Compression
- Koa.js - Authentication
- Koa.js - Sessions
- Koa.js - Cookies
- Koa.js - Static Files
- Koa.js - File Uploading
- Koa.js - Form Data
- Koa.js - Templating
- Koa.js - Cascading
- Koa.js - Error Handling
- Koa.js - Redirects
- Koa.js - Response Object
- Koa.js - Request Object
- Koa.js - HTTP Methods
- Koa.js - URL Building
- Koa.js - Routing
- Koa.js - Generators
- Koa.js - Hello World
- Koa.js - Environment
- Koa.js - Overview
- Koa.js - Home
Koa.js Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Koa.js - Sessions
HTTP is stateless, hence in order to associate a request to any other request, you need a way to store user data between HTTP requests. Cookies and URL parameters are both suitable ways to transport data between the cpent and the server. However, they are both readable on the cpent side. Sessions solve exactly this problem. You assign the cpent an ID and it makes all further requests using that ID. Information associated with the cpent is stored on the server pnked to this ID.
We ll need the koa-session, thus install it using −
npm install --save koa-session
We will put the koa-session middleware in place. In this example, we ll use the RAM to store sessions. Never use this in production environments. The session middleware handles everything, i.e. creating the session, setting the session cookie, and creating the session object in context object.
Whenever we make a request from the same cpent 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 cpent.
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.psten(3000);
What the above code does is, when a user visits the site, it creates a new session for the user and assigns a cookie. Next time the user visits, the cookie 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 following response.
![Session First](/koajs/images/session_first.jpg)
If you revisit the page, the page counter will increase. In this case, the page was refreshed 12 times.
![Session 12](/koajs/images/session_12.jpg)