পৃষ্ঠাসমূহ

.

Search Your Article

Total Pageviews

Thursday, March 2, 2017

Koa.js - Cookies

Cookies are simple, small files/data that are sent to client with a server request and stored on the client side. Every time the user loads the website back, this cookie is sent with the request. This helps us keep track of the users actions. There are numerous uses of HTTP Cookies.

  1. Session management
  2. Personalization(Recommendation systems)
  3. User tracking
To use cookies with koa, we have the functions: ctx.cookies.set() and ctx.cookies.get(). To set a new cookie lets define a new route in our koa app like:
var koa = require('koa');
var router = require('koa-router');
var app = koa();

_.get('/', setACookie);

function *setACookie(){
 this.cookie.set('foo', 'bar', {httpOnly: false});
}

var _ = router();

app.use(_.routes());

app.listen(3000);
To check if your cookie is set or not, just go to your browser, fire up the console, and enter:
console.log(document.cookie);
You will get the output like(you may have more cookies set maybe due to extensions in your browser):
"foo=bar"
Here is an example of the above:
The browser also sends back cookies every time is queries the server. To view a cookie on your server, on the server console in a route, add the following code to that route:
console.log('Cookies: foo = ', this.cookies.get('foo'));
Next time you send a request to this route, you'll get the ouput:
Cookies: foo = bar

Adding cookies with expiration time

You can add cookies that expire. To add a cookie that expires, just pass an object with property 'expires' set to the time when you want it to expire. For example,
var koa = require('koa');
var router = require('koa-router');
var app = koa();

_.get('/', setACookie);

function *setACookie(){
 //Expires after 360000 ms from the time it is set.
 this.cookies.set('name', 'value', { httpOnly: false, expires: 360000 + Date.now() });
}

var _ = router();

app.use(_.routes());

app.listen(3000);

Deleting existing cookies

To unset a cookie, simply set the cookie to an empty string. For example, if you need to clear a cookie named foo, use the following code:
var koa = require('koa');
var router = require('koa-router');
var app = koa();

_.get('/', setACookie);

function *setACookie(){
 //Expires after 360000 ms from the time it is set.
 this.cookies.set('name', '');
}

var _ = router();

app.use(_.routes());

app.listen(3000);
This will unset the said cookie. Note that you should leave the HttpOnly option be true when not using the cookie in client side code.

No comments:

Post a Comment