Git Product home page Git Product logo

cookie-session's Introduction

cookie-session

NPM Version NPM Downloads Build Status Test Coverage

Simple cookie-based session middleware.

A user session can be stored in two main ways with cookies: on the server or on the client. This module stores the session data on the client within a cookie, while a module like express-session stores only a session identifier on the client within a cookie and stores the session data on the server, typically in a database.

The following points can help you choose which to use:

  • cookie-session does not require any database / resources on the server side, though the total session data cannot exceed the browser's max cookie size.
  • cookie-session can simplify certain load-balanced scenarios.
  • cookie-session can be used to store a "light" session and include an identifier to look up a database-backed secondary store to reduce database lookups.

NOTE This module does not encrypt the session contents in the cookie, only provides signing to prevent tampering. The client will be able to read the session data by examining the cookie's value. Secret data should not be set in req.session without encrypting it, or use a server-side session instead.

NOTE This module does not prevent session replay, as the expiration set is that of the cookie only; if that is a concern of your application, you can store an expiration date in req.session object and validate it on the sever, and implement any other logic to extend the session as your application needs.

Install

This is a Node.js module available through the npm registry. Installation is done using the npm install command:

$ npm install cookie-session

API

var cookieSession = require('cookie-session')
var express = require('express')

var app = express()

app.use(cookieSession({
  name: 'session',
  keys: [/* secret keys */],

  // Cookie Options
  maxAge: 24 * 60 * 60 * 1000 // 24 hours
}))

cookieSession(options)

Create a new cookie session middleware with the provided options. This middleware will attach the property session to req, which provides an object representing the loaded session. This session is either a new session if no valid session was provided in the request, or a loaded session from the request.

The middleware will automatically add a Set-Cookie header to the response if the contents of req.session were altered. Note that no Set-Cookie header will be in the response (and thus no session created for a specific user) unless there are contents in the session, so be sure to add something to req.session as soon as you have identifying information to store for the session.

Options

Cookie session accepts these properties in the options object.

name

The name of the cookie to set, defaults to session.

keys

The list of keys to use to sign & verify cookie values, or a configured Keygrip instance. Set cookies are always signed with keys[0], while the other keys are valid for verification, allowing for key rotation. If a Keygrip instance is provided, it can be used to change signature parameters like the algorithm of the signature.

secret

A string which will be used as single key if keys is not provided.

Cookie Options

Other options are passed to cookies.get() and cookies.set() allowing you to control security, domain, path, and signing among other settings.

The options can also contain any of the following (for the full list, see cookies module documentation:

  • maxAge: a number representing the milliseconds from Date.now() for expiry
  • expires: a Date object indicating the cookie's expiration date (expires at the end of session by default).
  • path: a string indicating the path of the cookie (/ by default).
  • domain: a string indicating the domain of the cookie (no default).
  • partitioned: a boolean indicating whether to partition the cookie in Chrome for the CHIPS Update (false by default). If this is true, Cookies from embedded sites will be partitioned and only readable from the same top level site from which it was created.
  • priority: a string indicating the cookie priority. This can be set to 'low', 'medium', or 'high'.
  • sameSite: a boolean or string indicating whether the cookie is a "same site" cookie (false by default). This can be set to 'strict', 'lax', 'none', or true (which maps to 'strict').
  • secure: a boolean indicating whether the cookie is only to be sent over HTTPS (false by default for HTTP, true by default for HTTPS). If this is set to true and Node.js is not directly over a TLS connection, be sure to read how to setup Express behind proxies or the cookie may not ever set correctly.
  • httpOnly: a boolean indicating whether the cookie is only to be sent over HTTP(S), and not made available to client JavaScript (true by default).
  • signed: a boolean indicating whether the cookie is to be signed (true by default).
  • overwrite: a boolean indicating whether to overwrite previously set cookies of the same name (true by default).

req.session

Represents the session for the given request.

.isChanged

Is true if the session has been changed during the request.

.isNew

Is true if the session is new.

.isPopulated

Determine if the session has been populated with data or is empty.

req.sessionOptions

Represents the session options for the current request. These options are a shallow clone of what was provided at middleware construction and can be altered to change cookie setting behavior on a per-request basis.

Destroying a session

To destroy a session simply set it to null:

req.session = null

Saving a session

Since the entire contents of the session is kept in a client-side cookie, the session is "saved" by writing a cookie out in a Set-Cookie response header. This is done automatically if there has been a change made to the session when the Node.js response headers are being written to the client and the session was not destroyed.

Examples

Simple view counter example

var cookieSession = require('cookie-session')
var express = require('express')

var app = express()

app.set('trust proxy', 1) // trust first proxy

app.use(cookieSession({
  name: 'session',
  keys: ['key1', 'key2']
}))

app.get('/', function (req, res, next) {
  // Update views
  req.session.views = (req.session.views || 0) + 1

  // Write response
  res.end(req.session.views + ' views')
})

app.listen(3000)

Per-user sticky max age

var cookieSession = require('cookie-session')
var express = require('express')

var app = express()

app.set('trust proxy', 1) // trust first proxy

app.use(cookieSession({
  name: 'session',
  keys: ['key1', 'key2']
}))

// This allows you to set req.session.maxAge to let certain sessions
// have a different value than the default.
app.use(function (req, res, next) {
  req.sessionOptions.maxAge = req.session.maxAge || req.sessionOptions.maxAge
  next()
})

// ... your logic here ...

Extending the session expiration

This module does not send a Set-Cookie header if the contents of the session have not changed. This means that to extend the expiration of a session in the user's browser (in response to user activity, for example) some kind of modification to the session needs be made.

var cookieSession = require('cookie-session')
var express = require('express')

var app = express()

app.use(cookieSession({
  name: 'session',
  keys: ['key1', 'key2']
}))

// Update a value in the cookie so that the set-cookie will be sent.
// Only changes every minute so that it's not sent with every request.
app.use(function (req, res, next) {
  req.session.nowInMinutes = Math.floor(Date.now() / 60e3)
  next()
})

// ... your logic here ...

Using a custom signature algorithm

This example shows creating a custom Keygrip instance as the keys option to provide keys and additional signature configuration.

var cookieSession = require('cookie-session')
var express = require('express')
var Keygrip = require('keygrip')

var app = express()

app.use(cookieSession({
  name: 'session',
  keys: new Keygrip(['key1', 'key2'], 'SHA384', 'base64')
}))

// ... your logic here ...

Usage Limitations

Max Cookie Size

Because the entire session object is encoded and stored in a cookie, it is possible to exceed the maximum cookie size limits on different browsers. The RFC6265 specification recommends that a browser SHOULD allow

At least 4096 bytes per cookie (as measured by the sum of the length of the cookie's name, value, and attributes)

In practice this limit differs slightly across browsers. See a list of browser limits here. As a rule of thumb don't exceed 4093 bytes per domain.

If your session object is large enough to exceed a browser limit when encoded, in most cases the browser will refuse to store the cookie. This will cause the following requests from the browser to either a) not have any session information or b) use old session information that was small enough to not exceed the cookie limit.

If you find your session object is hitting these limits, it is best to consider if data in your session should be loaded from a database on the server instead of transmitted to/from the browser with every request. Or move to an alternative session strategy

License

MIT

cookie-session's People

Contributors

alvarotrigo avatar dougwilson avatar fishrock123 avatar fritx avatar gartz avatar hacksparrow avatar jcoimbra-daitan avatar jonathanong avatar madarche avatar ostefanini avatar resonance1584 avatar shubham04112002 avatar vice avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cookie-session's Issues

How to access Session.isNew?

The docs say that Session.isNew is "true" when the session is new. I've tried all of the following:

var session = require('cookie-session');
...
app.use(session({
    keys: ['key1', 'key2']
  }));

app.use(function (req, res, next) {
  var isNew = Session.isNew; // ReferenceError: Session is not defined
  var isNew = session.isNew; // undefined
  var isNew = req.session.isNew; // undefined
...
}

Where do I find this elusive isNew flag?

Secure CookieSession when using iisnode

I'm using node with IIS by using iisnode and I'm having troubles setting the CookieSession option secure:true.

I'm using HTTPS on IIS and I'm redirecting any HTTP to HTTPS.
But evenw ith this, if I set the CookieSession option secure:true, the session won't have any content after login.

secure: a boolean indicating whether the cookie is only to be sent over HTTPS (false by default for HTTP, true by default for HTTPS).

I'm forced to use secure:false to make it work. Why is it?

Express lose session after redirect when cookie-session path is different from default

Hi again. I have the following problem: I've changed session cookie path from default '/' to '/test'.

app.use(session({
  resave: true,
  name: 'test.connect.sid',
  keys: ['key1', 'key2'],
  secret: 'testsecret',
  secure: false,
  domain: 'localhost',
  path: '/test'
}));

My /test1 route sets test string to the session.

app.get('/test1', function(req, res, next) {
    req.session.test = 'test';
    res.redirect('http://localhost:3000/test2');
});

Before redirect I have a test string in request session, but after redirect to '/test2' request session is undefined.

app.get('/test2', function(req, res, next) {
    console.log('test2', req.session.test); // undefined
    res.send(req.session.test);
});

When session cookie path is default ('/') all works as expected. But I need a different cookie paths.
May be you know how to fix it?

Error: Cannot find module 'cookie-signature'

Error: Cannot find module 'cookie-signature'
  at Function.Module._resolveFilename (module.js:338:15)
  at Function.Module._load (module.js:280:25)
  at Module.require (module.js:364:17)
  at require (module.js:380:17)
  at Object.<anonymous> (/home/embrujado/projects/expressjs4/node_modules/express-session/index.js:15:17)
...

Count example in page is increasing by two.

I tried to test the count example of this module and noticed that it is increasing by two.

I am testing on my local machine no nginx.

It's almost as if my client machine is making a request twice behind the scenes.
What might be the issue?

EDIT: This is a copy of the http header that is sent to the client. Interesting that there are two Set-Cookie

HTTP/1.1 200 OK
Connection: keep-alive
Date: Tue, 14 Apr 2015 20:54:02 GMT
Set-Cookie: finda-sess=eyJjb3VudCI6MzN9; path=/; httponly
Set-Cookie: finda-sess.sig=g9IWmpQ9GvzHHQnDyTeOfAhauto; path=/; httponly
Transfer-Encoding: chunked
X-Powered-By: Express

Add warning if cookie size exceeds 4000 bytes

Currently if the cookie exceeds 4000 bytes it will fail to store in most modern browsers. This results in the user either repeatedly sending an older smaller session object, or having no session at all.

Cookie size limits are determined by the user-agent, so this should probably just be a console warning, not a failure or exception.

No cookie set with connect-livereload

When using express 4.1.1, the cookie session middleware does not seem to be able to set the set-cookie header. For example, following the main example

var cookieSession = require("cookie-session");
...
app.use(cookieSession({
        "name" : "sid",
        "keys" : [ "bla" ]
}));

Debugging the response, we found out that no cookie was set.

req.sessionOptions is always empty

Hello,

Just executing the sample code you provide I cannot access the cookie options via req.sessionOptions.

For instance: if I am going to use it via a simple REST API to authenticate browsers' users I don't know if their cookie expired and how to request a new one.

Thanks


For all matters, this is the code I am using to check it:

var cookieSession = require('cookie-session')
var express = require('express')

var app = express()

app.set('trust proxy', 1) // trust first proxy
var opt = {
  name: 'session',
  keys: ['key1', 'key2'],
  // maxAge: 24 * 60 * 60 * 1000, // 24 hours
  expires: new Date(new Date().getTime() + 1*60000) // 30 minutes
};

console.log(JSON.stringify(opt))

app.use(cookieSession(opt))

app.get('/', function (req, res, next) {
  // Update views
  req.session.views = (req.session.views || 0) + 1

  console.log(req.sessionOptions)

  // if (req.sessionOptions.expires < new Date().getTime()) {
    console.log('session: ' + JSON.stringify(req.session))
    res.end(req.session.views + ' views') // Write response
  // }
  // else {
  //   req.session = null
  // }
})

app.listen(3000)

wildcard subdomains

I saw that for express-session you could put a "wildcard" for subdomains like so:

   app.use(cookieSession({
        name: 'lectal-cookie',
        secret: 'Bartholomew-the-Apostle',
        domain: '.herokuapp.com'  // << with express-session you can do this
    }));

is this possible with cookie-session?

How can we make the cookie available for any subdomain of herokuapp.com? Or perhaps more securely for just two or three subdomains of herokuapp.com?

thanks :)

keys option not documented

Keys are provided in the example, but not documented. It would be good to make clear what options are required to make cookie-session secure.

Renewing the session

How are we suppose to renew the session?

Using req.sessionOptions.maxAge = req.session.maxAge within a middle-ware?

How do I set maxAge

How do I set the maxAge property on the cookies/sessions that get created? jed/cookies only provides "expires" as a date.

HowTo : Share session between multiple routes files

Hi!

I need to use sessions for my web app, but I don't understand how to use cookie-session between my app.js (express JS server), routes/index.js and routes/session.js files.

routes/index.js

Used to navigate throw the web app.

var express = require('express');
var router = express.Router();
var printSession = require('../web_modules/printSession');

//- GET home page.
router.get('/', function(req, res, next) {
    req.session.lastPage = '/home';
    res.render('home');
    printSession(req.session);
});

router.get('/exit', function(req, res, next) {
    delete req.session.lastPage;
    req.session.reset();
    res.render('home');
});

module.exports = router;

routes/session.js

Used to access to some session variables from the client in javascript. It's a REST API.

var express = require('express');
var router = express.Router();
var printSession = require('../web_modules/printSession');

router.get('/:var?', function(req, res, next) {
    if(req.params[0]){
        var variable = req.params[0];
        res.status(200);
        res.send(req.session[variable ]);
        console.log(req.session[variable ]);
        printSession(req.session);
    }else{
        res.status(200);
        res.send(req.session);
        printSession(req.session);
    }
});

module.exports = router;

app.js

var express = require('express');
var routes = require('./routes');
var session = require('./routes/session');
[...]
var cookieParser = require('cookie-parser');
var cookieSession = require('cookie-session');
[...]
var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'public/views'));
app.set('view engine', 'ejs');
app.use(favicon(__dirname + '/public/favicon.png'));
app.use(logger('dev'));
app.use(methodOverride());
app.use(cookieSession ({
                    cookieName: 'session'
                    , secret: randomstring.generate()
                    , httpOnly: true
                    , ephemeral: true
                    , duration: 30 * 60 * 1000
                    , activeDuration: 5 * 60 * 1000
                    // , secure: true
              }));
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));


app.use('/', routes);
app.use('/session', session);

I would like to use the same session between routes/index.js and routes/session.js in order to use and modify data in it.
But after some tests, variable can be added to the session in routes/index.js but can't be added from routes/session.js: When a variable is added from routes/session.js, it is not existant in routes/index.js.

Thanks for your help!

Regards.

Capacity limit

I was reading about the difference between using a Session and a Cookie Session and it seems cookie sessions are only recommended if you want to have a small session data in it.

The session middleware implements generic session functionality with in-memory storage by default. It allows you to specify other storage formats, though.

The cookieSession middleware, on the other hand, implements cookie-backed storage (that is, the entire session is serialized to the cookie, rather than just a session key. It should really only be used when session data is going to stay relatively small.

I'm looking for a solution to implement sessions in the server side of a Windows machine and it seems express-session is not ideal for it as its not ready to work on production with the default storage module, and other modules like Redis won't be supported in Windows. Plus I'm just looking for a simple local solution.

So I was just wondering what's the recommended data limit for which cookie-session should be used.

2.0.0-alpha.1 not in NPM

The latest version is not actually in NPM.
Whenever I try to install the latest alpha version with npm the package.json file gets updated with "cookie-session": "^2.0.0-alpha.1" but the code belongs to 1.2.0

npm install cookie-session --save

Also, it would be nice to have a version number in the file. I had to use a code comparison tool to realise the version was not the correct one.

Purpose of the keys param?

After reading the documentation I don't have it very clear what is the keys parameter for in the cookie-session configuration.

I'm not an expert on cookies and the description doesn't help me much on that regard.

keys
The list of keys to use to sign & verify cookie values. Set cookies are always signed with keys[0], while the other keys are valid for verification, allowing for key rotation.

But it seems to be a compulsory field, if I don't add it I get an error:

C:\inetpub\wwwroot\app\node_modules\cookie-session\index.js:55
if (!keys && opts.signed) throw new Error('.keys required.');

So I ended up using keys: ['key1', 'key2'] as in the examples, but I have no idea why.

Rename "key" to "name".

"key" is too easily confused with "keys".

We can still set it from options.key if it exists as fallback.

encrypt cookies

Signing is nice, but a better thing might be to just encrypt the cookies outright. This serves the purpose of signing and also hiding the session details from user inspection.

Release 2.0.0-alpha as stable?

It's been like 8 months now since -alpha was released... Should the alpha flag be removed and it published as stable?

Not working

I am using cookie-session and the cookie does not get created on it its own when i browse any page in my web app.
Code -

var cookieSession = require('cookie-session')//http://goo.gl/IImRVj
var cookieParser = require('cookie-parser');
app.use(modules.cookieParser());// read cookies (needed for auth)
app.use(modules.cookieSession({
  name: 'session',
  keys: ['mysecretty'],
  maxAge : 365 * 24 * 60 * 60 * 1000
}))

However a cookie of name "session is created when i add this line -

app.use(function(req, res, next) {
  req.session.foo = 'bar';
  next();
});

I do not use livereload in my web app

Conflict with "connect-livereload"

I'm not too sure why, but cookie-session doesn't work if used after connect-livereload. Let me show you what I mean with a simple example.

This works:

var express = require('express');
var app = express();
var cookieParser = require('cookie-parser');
var session = require('cookie-session');

app.use(cookieParser());
app.use(session({keys: ['mysecret']}));

This instead doesn't work (session values can't be set):

var express = require('express');
var app = express();
var livereload = require('connect-livereload');
var cookieParser = require('cookie-parser');
var session = require('cookie-session');

app.use(livereload());
app.use(cookieParser());
app.use(session({keys: ['mysecret']}));

Any hint where the problem might be?

Thanks!

Cookie not set in response when setting secure:true

Hello,

When running the following app.js:

var cookieSession = require('cookie-session')
var helmet = require('helmet');
var express = require('express')

var app = express()

app.use(helmet());
var oneYearInSeconds = 31536000;
app.use(helmet.hsts({
  maxAge: oneYearInSeconds,
  includeSubDomains: true,
  force: true
}));

var expiryDate = Date.now() + 60 * 60 * 1000;
app.use(cookieSession({
  name: 'session',
  secret: '10dfaf09-cf6f-43a9-b40b-4eaacbcceb8a',
  maxAge: expiryDate,
  secure : true
  // secureProxy: true, // Deprecated when using 2.0.0-alpha. Says to use secure option but that stops passing on cookies. When set to true, the cookie is set to Secure. If commented out, cookie not set to Secure
}))

app.get('/', function (req, res, next) {
  // Update something in the session, needed for a cookie to appear
  req.session.views = (req.session.views || 0) + 1

  // Write response
  res.end(req.session.views + ' views')
})

app.listen(3000)

When I now curl it:
vagrant$ curl -c - -v http://localhost:3000/
Connected to localhost (127.0.0.1) port 3000 (#0)

GET / HTTP/1.1
User-Agent: curl/7.37.1
Host: localhost:3000
Accept: /

< HTTP/1.1 200 OK
< X-Content-Type-Options: nosniff
< X-Frame-Options: SAMEORIGIN
< X-Download-Options: noopen
< X-XSS-Protection: 1; mode=block
< Surrogate-Control: no-store
< Cache-Control: no-store, no-cache, must-revalidate, proxy-revalidate
< Pragma: no-cache
< Expires: 0
< Strict-Transport-Security: max-age=31536; includeSubDomains
< Date: Tue, 13 Dec 2016 11:27:37 GMT
< Connection: keep-alive
< Content-Length: 7
<
Connection #0 to host localhost left intact

You see no cookies are added nor set. When I comment out secure:true and set secureProxy : true, then a cookie is returned, you'll see something like:

#HttpOnly_localhost FALSE / TRUE 2961374488 session eyJ2aWV3cyI6MX0=
#HttpOnly_localhost FALSE / TRUE 2961374488 session.sig DJaPtrG-tmTnVr33fOWXqWGnVlw

See also my comment at the end of the secureProxy field.

Versions used:
node js: 6.7.0
express: 4.13.30
cookie-session: 1.2.0
helmet: 0.14.0

Am I doing something wrong? Or maybe it's helmet being in the way in some form? Update: nope, when commenting out the helmet parts, same behavior.

Publish new version

It looks like 2.x still isn't published. I really want that change to include underscore prefixed properties.

Cookie contents

Hi

I was using this module implicitely via express 3.0.
I'm now trying to migrate and the only problem Iingering is with this module.

In the past I was calling something like:

app.use(express.cookieSession({
  key:'sid', secret:'dog'
}));

Which became:

app.use(require('cookie-session')({
  name:'sid', secret:'dog'
}));

The cookie value had a recoverable JSON fragment, which may or may not be correct to use (you tell me). The point is I was using the decoding the JSON in the client and I could have the user data without a specific request.

Old example:

s%3Aj%3A%7B%22passport%22%3A%7B%22user%22%3A22aflesler%40gmail.com%22%7D%7D.TE0pjy88BSqQLh5835U4C3ytwJmkuhUmpSkGf7e1s5o

The cookie value is a different string, seems to have went through base64:

eyJwYXNzcG9ydCI6eyJ1c2VyIjoiYXJpZWxAYW1iZXJhZHMuY29tIn19

My question is: is this due to a recent change in the encoding logic or is because I'm using the settings wrong? is there a way to extract the JSON out of this new cookie value?

Thanks!

Delete session after closing browser

I didn't manage to remove the session after the browser gets closed.

My initialization:

app.use(cookieSession({
  maxAge: 8*60*60*1000, //8 hours
  httpOnly: true,
  secure: false,
  secureProxy: true,
  keys: ['key1', 'key2']
}));

expires: a Date object indicating the cookie's expiration date (expires at the end of session by default).

Cannot set the .sig cookie's expiry

This may not be a bug, but just me not knowing what to do.

So I want to update my session cookie everytime my users to an api call and he/she has ticked the "remember me" checkbox on login. So far, I have been able to update the expiry on the express:sess cookie just fine. Now my issue is I cannot update the expiry of my express:sess.sig cookie. When my user quits his/her browser, the express:sess.sig cookie disappears and my user will no longer have a valid session (even though he/she still has the express:sess cookie)

Am I doing something fundamentally wrong here?

In your docs you say this: "Other options are passed to cookies.get() and cookies.set() allowing you to control security, domain, path, and signing among other settings."
Where do we actually change what cookies.set() does? Maybe its in cookies.set() where I should add 7 days to the expiry?

How to set the session options

The documentation doesn't seem to be very clear to me.
It says

Other options are passed to cookies.get() and cookies.set()

  • What is cookies there?
  • Does it mean we have to use set to set the options we want?

I was trying to use cookieSession as express-session, but it seems that's not the way it works:

var cookieSession = require('cookie-session');

app.use(cookieSession({
  maxAge: 20*60*1000, //20 mins
  httpOnly: true,
  secure: true,
  secureProxy: true,
  keys: ['key1', 'key2']
}));

Cookie path

Hi. I'm trying to save cookies by path like this:

app.use(session({
  name: 'test.connect.sid',
  keys: ['key1', 'key2'],
  cookie: {
    secure: false,
    domain: 'localhost',
    path: '/test',
    expires: expiryDate
  }
}));

But when I look on cookies in browser I see the following:
cook
Path is default, '/', expire date is default too.

Using cookie-session with express.io

I'm trying to use _cookie-session_ with _express.io_ and so avoid using _MemoryStore_

This is my code :

express = require('express.io');
app = express().http().io();
require('express.io-middleware')(app);
app.use(express.cookieParser());
var session = require('cookie-session');
app.use(express.session({secret: 'hygdfreiliu'}));
app.io.use(function(req, next) {
    if (req.session.user || (req.io.event === "user:login")) {
        try {
            next();
        }
        catch(err){
            __debug.error('REQUEST_ERROR');
            var result = new (require("./core/result.js"))();
            result.notification.error("#REQUEST_ERROR");
            req.io.respond(result);
        }
    }
});

An exception occurs:

TypeError: object is not a function
    at /home/dev/svn/webmail2/node_modules/express.io/compiled/index.js:107:20
    at iterate (/home/dev/svn/webmail2/node_modules/express.io/node_modules/async/lib/async.js:108:13)
    at Object.async.forEachSeries (/home/dev/svn/webmail2/node_modules/express.io/node_modules/async/lib/async.js:124:9)
    at Manager.<anonymous> (/home/dev/svn/webmail2/node_modules/express.io/compiled/index.js:106:24)
    at Manager.authorize (/home/dev/svn/webmail2/node_modules/express.io/node_modules/socket.io/lib/manager.js:925:31)
    at Manager.handleHandshake (/home/dev/svn/webmail2/node_modules/express.io/node_modules/socket.io/lib/manager.js:801:8)
    at Manager.handleRequest (/home/dev/svn/webmail2/node_modules/express.io/node_modules/socket.io/lib/manager.js:616:12)
    at Server.<anonymous> (/home/dev/svn/webmail2/node_modules/express.io/node_modules/socket.io/lib/manager.js:119:10)
    at Server.emit (events.js:98:17)
    at HTTPParser.parser.onIncoming (http.js:2108:12)

How can i avoid this problem ?

Repeated field in `package.json`

The field dependencies repeats in package.json

  "dependencies": {
    "cookies": "~0.4.0"
  },
  "devDependencies": {
    "connect": "*",
    "mocha": "*",
    "should": "*",
    "supertest": "*"
  },
  "license": "MIT",
  "dependencies": {
    "debug": "*"
  },

Let's fix it!

maxAge don't set from config

Hello, sorry for my bad eng. I have a trouble with maxAge property, that work only from direct input, but not from config.

Example:

app.use(cookieSession({
  name: 'sessiondata',
  keys: ['key1', 'key2'],
  cookie: { 
            maxAge: 1 // set the default value
          }
    })
);
app.get('/login', function(req, res, next) {
  res.cookie('id', 'lol');  //default maxage=1 dont work
  res.cookie('id2', '2222222', { maxAge: 1222});//its work
  res.send(req.cookies.id+req.cookies.id2); //id = lol    id2=undifened (if wait a few seconds and update page)
});

cookie-session seems to ignore the overwrite option

I want my user's session cookie to be updated every time they interact with the site, but cookie-session will only update the cookie if the contents has changed. From the documentation it seems that the overwrite option is designed to allow the cookie to be updated which each request.

This would allow the us to set a semi-short expiration time and update it with every interaction without needing to change the contents of the cookie. The only work around I've been able to come with right now is to write another property containing a new Date() object with each request, but this feels very hack-y-ish to me.

In the code, cookie-session reads in the overwrite option, but then just ignores it when deciding whether or not to right the cookie. The overwrite option seems to just be ignored in the code altogether. I guess it gets passed to the cookies module with all of the other options, but the behavior is ignored in the native session-cookie code.

Using express flash does not trigger a session update

The following happens in express 4:

req.flash('error', error.toString());
assert(req.session.isChanged == false)
req.session.foo = req.session.flash;
assert(req.session.isChanged == true)

But even doing that doesn't persist the data, both foo and flash get serialized as empty arrays. But if I set foo manually to an array or object then that does work.

The problem with example in README.md

In example: Simple view counter example

There a statement req.session.views = n++, since we set req.session.views with n++, the req.session.views will always be the old value of n, and we'll get 1 views in every request.

we should change the statement to

n++
req.session.views = n

Cookie-options not set(again)

It's me again :)

Maybe i do something wrong, but default settings still not working.

Here is the code:

var cookieSession = require('cookie-session');
app.use(cookieParser());

app.use(cookieSession({
    name: 'session',
    secret: 'dexter',
    cookie: {       
        secure: true,
        httpOnly: true,
        maxAge : 1111
    }
    })
);

app.get('/login', function(req, res, next) {
req.session.someid = 'bar';
res.render('login');
});

And there is chrome developers-tool(F12/Network):

Connection:keep-alive
Cookie:session=eyJycnIiOiJkc3NzcyIsInRlc3QiOiJkc3NzcyIsImZvbyI6ImJhciIsInNvbWVpZCI6ImJhciJ9; session.sig=RoXWvswDSKg8qoZS5ePtVn1jl3Q

maxAge is not set to 1111 :(

What i do wrong?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.