Using sessions to store data
While we can use cookies for storing information relevant to a user, it starts to become unwieldy as their number increases and the size of the data grows. That's where sessions come in.
Sessions, however, should not be mistaken for an independent replacement for cookies. In fact, the sessions API leverages a cookie to identify a user's session.
There are two broad ways of implementing sessions in Express: using cookies and using a session store at the backend. Both of them add a new object in the request object named session
, which contains the session variables.
No matter which method you use, Express provides a consistent interface for interacting with the session data.
Cookie-based sessions
Using the fact that cookies can store data in the user's browser, a session API can be implemented using cookies. Express comes with a built-in middleware called cookieSession
that does just that.
Load the
cookieParser
middleware with a secret, followed by the cookieSession...