Reputation: 103
I am a beginner in NodeJS. I was working on a simple session-based user authorization to get a taste and it is working perfectly fine as there are plenty of examples around the internet which are easy to understand. I used express-session and the following code:
app.use(session({
key: 'userid',
secret: 'hojoborolo',
resave: false,
saveUninitialized: false,
cookie: {
expires: 600000
}
}));
created a simple session which then I was able to access using req.session
object.
I went to express-session documentation to get more information on the session data. It clearly said there "Session data is not saved in the cookie itself, just the session ID. Session data is stored server-side. The default server-side session storage is MemoryStore."
Like PHP, where simple PHPSESSID
session data is stored in a file under the default temporary directory /tmp
in server-side, where and how MemoryStore
stores the data in server-side and utilizes it? How MemoryStore
works basically?
P.S.: Coming from a PHP background
Upvotes: 9
Views: 9180
Reputation: 8276
You are on the right track with getting started with sessions, but you will want to switch to another option than the built-in MemoryStore if you're creating a production application. As you've seen in the documentation:
Warning The default server-side session storage, MemoryStore, is purposely not designed for a production environment. It will leak memory under most conditions, does not scale past a single process, and is meant for debugging and developing.
MemoryStore literally acts as it sounds - it stores the session in memory for the process, meaning if you restart your application you will lose the session. PHP requests are self-contained; each request spawns a new process which ends when the request is complete, therefore sessions by default have to be stored in somewhere like a temporary file. With Node.js/Express there is one continually running process which handles all requests that come in, so you can store sessions in the process's memory. You could conceptually think of it as no different than the app
variable or any other global in your application.
So, while storing sessions in memory works, if your application restarts for any reason you will lose all sessions which makes it unsuitable for a production environment (as well as the fact that it leaks memory). It is useful for testing to make sure your session code is working, but you will want to switch to a compatible session store that can handle sessions persistently (which could be in /tmp as you suggested, a database, etc.)
Upvotes: 6