ParisNakitaKejser
ParisNakitaKejser

Reputation: 14849

Easy way to use session in Node.js

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.

Upvotes: 0

Views: 1167

Answers (1)

Thomas Bormans
Thomas Bormans

Reputation: 5362

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.

Upvotes: 2

Related Questions