hapi-cookie
v0.1.0
Published
Creates cookies for the hapi framework.
Downloads
18
Readme
#Hapi-cookie ##Welcome to my first hapi module
hapi-cookie simply sets a cookie in the response before it goes out.
I developed this module because I was having problems setting cookies. Hapi provides the server.state / plugin.state to set a "state" cookie which works perfectly. The problem was that I couldn't set things like expiration, path, domain etc.. just a name and value. So, I started looking for a way to do this on my own.
##How does hapi-cookie work?
The server.ext seemed like a logical place to start. There, I trigger off the "onPreResponse" event and extend "request.response.headers" with (possibly multiple) "Set-Cookie" instances. It's relatively simple and a little embarrassing how long it took me to come up with it.
##How to use this module
In your manifest.json:
{
"servers" : [
{
"port": {{whatever port number}},
"options" : {
{{whatever options you want to set}}
}
}
],
"plugins" : {
"hapi-cookie" : {}
}
}
Of course your manifest might be much larger with many more plugins and servers.
Then use the single exposed API to set a cookie:
var hapiCookie = plugin.plugins['hapi-cookie'];
/*
hapiCookie.setCookie(
String nameOfCookie,
String valueOfCookie,
String GMTformat,
String path,
String domain,
Boolean isSecure,
Boolean is HTTPOnly,
callback(error, cookie value){}
)
*/
// for example
var dur = 100000000; // add some tiem so the cookie doesn't expire right away
var dte = new Date(new Date().getTime()+dur).toUTCString();
hapiCookie.setCookie("newCookie", "cookieValue", dte, "myDomain.com", "/", true, true, function(e, cookieVal){
if(e){
console.log("The cookie was not set");
} else {
console.log("Cookie Set : "+cookieVal);
}
}
Future changes:
There is also the possibility of using request.headers.state to attach a "Set-Cookie". Might want to fully investigate using that instead. Or give users the option.
Add more API's to add other headers?