Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

NodeJS - Framework for stateless sessions?

NodeJS - Framework for stateless sessions?

Problem

Is there a framework to support fully client-managed sessions? In other words, instead of storing just the signed pid in the cookie (as Express does), store all context... so that you can manage state across clusters without the requirement to persist.

Problem courtesy of: Robert Christian

Solution

There is express middleware which supports this:

https://github.com/expressjs/cookie-session

cookieSession()

Provides cookie-based sessions, and populates req.session. This middleware takes the following options:

  • name - cookie name defaulting to "session"
  • keys - list of secret keys to prevent tampering
  • secret - used as single key if keys are not specified
  • options - additional options such as secure, httpOnly, maxAge, etc.

Middleware:

var cookieSession = require('cookie-session')
...
app.use(cookieSession({
    name: "my_session_cookie",
    secret: "dont_tell_anybody_the_secret_and_change_it_often",
    options: { ... }
));

app.use((req, res, next) => {
    // set options on req.session before your response goes out
    req.session.viewCount = (req.session.viewCount || 0) + 1;
    res.end(`You viewed the page ${req.session.viewCount} times.`);
});

To clear a cookie simply assign the session to null before responding:

req.session = null
Solution courtesy of: Robert Christian

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

NodeJS - Framework for stateless sessions?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×