Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use sessions in express, couchDB, and node.js

Tags:

so I basically want to use sessions to store the users name and check to see if the user logged in or not. If not, the page will redirect to the login page.

I am using Node.js,express,and couchDB.

Here is how i set up my session so far

var MemoryStore = require('connect').session.MemoryStore; app.use(express.cookieParser()); app.use(express.session({      secret: "keyboard cat",      store: new MemoryStore({          reapInterval: 60000 * 10     }) })); 

To store something in the session, i use the following code right?

req.session = {user:name); 

So the session variable seems to work on my login page. I successfully store the user's name into the session However, when I try to access the session variable on another page, it gives me the error

Cannot read property 'user' of undefined 

all i'm doing is:

if (req.session.user){ 

Why is this error happening? are sessions not global to the whole app? Or am I missing something entirely here.

Thanks in advance!

like image 227
Ernesto11 Avatar asked Apr 08 '11 18:04

Ernesto11


People also ask

How do Sessions work in express?

Overview. Express. js uses a cookie to store a session id (with an encryption signature) in the user's browser and then, on subsequent requests, uses the value of that cookie to retrieve session information stored on the server.

How do I create a session in express?

In the following example, we will create a view counter for a client. var express = require('express'); var cookieParser = require('cookie-parser'); var session = require('express-session'); var app = express(); app. use(cookieParser()); app. use(session({secret: "Shh, its a secret!"})); app.

How do I handle multiple sessions in Node js?

Here, since sess is global, the session won't work for multiple users as the server will create the same session for all the users. This can be solved by using what is called a session store. We have to store every session in the store so that each one will belong to only a single user.


2 Answers

If you're doing app.use(app.router) before the lines that set up the cookie and session handling, try moving it to after them. That fixed the same problem for me.

like image 150
Mike Scott Avatar answered Sep 22 '22 07:09

Mike Scott


I was trying to solve the exact same problem for he last few hour.

Try initializing your server like that:

var app = express.createServer( express.cookieParser(), express.session({ secret: "crazysecretstuff"})   ); 

That should work.

like image 31
marc_d Avatar answered Sep 24 '22 07:09

marc_d