mozilla / node-client-sessions

secure sessions stored in cookies
Mozilla Public License 2.0
759 stars 104 forks source link

Using client-sessions without Connect/Express #110

Open ohenepee opened 8 years ago

ohenepee commented 8 years ago

Please can client-sessions be used with Raw HTTP(s)?

ottiker commented 8 years ago

Hi! We use this module without connect. See here for an example.

But basically you can just pass the req and res objects from node's http.createServer to the client session handler.

var sessions = require("client-sessions");
var http = require('http');

var requestSessionHandler = sessions({
    cookieName: 'mySession', // cookie name dictates the key name added to the request object
    secret: 'blargadeeblargblarg', // should be a large unguessable string
    duration: 24 * 60 * 60 * 1000, // how long the session will stay valid in ms
    activeDuration: 1000 * 60 * 5 // if expiresIn < activeDuration, the session will be extended by activeDuration milliseconds
});

http.createServer(function (req, res) {
    requestSessionHandler(req, res, function () {
        if (req.mySession.seenyou) {
            res.setHeader('X-Seen-You', 'true');
        } else {
            // setting a property will automatically cause a Set-Cookie response
            // to be sent
            req.mySession.seenyou = true;
            res.setHeader('X-Seen-You', 'false');
        }
    });
}).listen(8000); 

I didn't test this example, but it should show you how it can be done.

..maybe there are better ways to use client-sessions without connect?