Mani Bharathy
Mani Bharathy

Reputation: 117

Node express server session management middleware?

I want to do only cookie based authentication for my app. No pwd or email need to be given. It is like the guest user feature in some webapps (like discord). You can use the app like a logged in user as long as you have that cookie (or local storage). I find this very seamless and I don't want to put up signup barrier to the visitors.

I want a middleware, which does the following : If request does not have a session id, it has to create a new session (by adding new document in sessions collection in mongodb, and setting the field session_id with random string)

If the request has cookie, it has to parse the cookie and set in request object. Even better, it gets the session object from db and set it in request object.

Is there anything right out of the box that does this? Or any other ways to easily achieve this?

Upvotes: 0

Views: 264

Answers (1)

jfriend00
jfriend00

Reputation: 707158

express-session with a mongodb data store will do that pretty much right out of the box. There are multiple session store options for mongodb here. One of them is even maintained by the mongodb team.

In a nutshell, express-session will check for an incoming session cookie. If one exists, it will look up the session ID in the session store and find the session object for that ID. If there is no cookie or the DB has no session for that ID, it will make sure there's a cookie and create a new session for it. That session will be available as req.session for that request for all request handlers and middleware downstream of the session middleware.

You will need to age away old sessions from mongodb because if you're not attaching any login to them, then lots of the sessions will get permanently orphaned either when the user never comes back to your site or when the user's cookie ages away. And, the same user from multiple devices will cause multiple separate sessions to be created (which is a by-product of the auto-session-creation and login-free design).

Upvotes: 1

Related Questions