Koa.js – Cookies


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 keep track of the users actions. There are numerous uses of HTTP Cookies.

  • Session management
  • Personalization(Recommendation systems)
  • User tracking

To use cookies with Koa, we have the functions: ctx.cookies.set() and ctx.cookies.get(). To set a new cookie, let’s define a new route in our Koa app.

var koa = require(''koa'');
var router = require(''koa-router'');
var app = koa();

_.get(''/'', setACookie);

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

var _ = router();

app.use(_.routes());
app.listen(3000);

To check if the cookie is set or not, just go to your browser, fire up the console, and enter −

console.log(document.cookie);

This will produce the following output (you may have more cookies set maybe due to extensions in your browser).

"foo = bar"

Here is an example of the above.

Cookie

The browser also sends back cookies every time it 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 following output.

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 the 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 to be true when not using the cookie in the client side code.

Advertisements

”;

Leave a Reply

Your email address will not be published. Required fields are marked *