0

i trying to get session in Node.js to working, i reading and trying a lot about session in Node.js, in PHP i can use $_SESSION['key'] = $value; but i can find how its working in Node.js.

i have looking on express-session and its look pretty complex to handle cookies and there using MongoDB or Redis to store session.

so i will ask about somarby can share sample on a easy way to handle session by using ExpressJS?

becures if i use express-session i need to use node-uuid to generante my owen uuid v4 key.

so hope i can be helping here, its what i need to complete my user login.

3
  • express-session is really not that hard and you definitely do not need node-uuid. Why do you think that? Commented Nov 15, 2015 at 20:20
  • You don't need to use MongoDB or Redis store. There are File stores. Commented Nov 15, 2015 at 20:21
  • I can't find guides for it all guides i have found use a db or use a complex metode, can sombody help widt samples or link to easy and good guides :) Commented Nov 15, 2015 at 20:22

1 Answer 1

2

I use express-session together with connect-mongo for storing the sessions in MongoDB. My code looks like this:

var express = require('express');
var session = require('express-session');
var mongoStore = require('connect-mongo')({
    session: session
});

var cookieExpiration = 30 * (24 * 60 * 60 * 1000); // 1 month
app.use(session({
    // When there is nothing on the session, do not save it
    saveUninitialized: false,
    // Update session if it changes
    resave: true,
    // Set cookie
    cookie: {
        // Unsecure
        secure: false,
        // Http & https
        httpOnly: false,
        // Domain of the cookie
        domain: 'http://localhost:3001',
        // Maximum age of the cookie
        maxAge: cookieExpiration
    },
    // Name of your cookie
    name: 'testCookie',
    // Secret of your cookie
    secret: 'someHugeSecret',
    // Store the cookie in mongo
    store: new mongoStore({
        // Store the cookie in mongo
        url: 'mongodb://localhost/databaseName',
        // Name of the collection
        collection: 'sessions'
    })
}));

For all the options of express-sessions, see the docs.

Now you can store all your session data on req.session. Everything you put on your session, will also be saved in the MongoDB. Make also sure you are sending your cookie from your front-end, otherwise your session will always be empty.

Sign up to request clarification or add additional context in comments.

1 Comment

Cool, and i replace it with data from MinusFour to "File stores" and now i can work width session, thanks a lot i have learn a lot in this weekend ^^

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.