I am new with Express
. As Express 4.x
has removed bundled middlewares. Any middleware I want to use should be required. When I read the README with express-session and cookie-session on github, I feel it hard to understand the difference.
So I try to write simple code to figure it out. I run twice for each middleware.
var express = require('express') , cookieParser = require('cookie-parser') , session = require('cookie-session') , express_sess = require('express-session') , app = express(); app.use(cookieParser()) app.use(session({ keys: ['abc'], name: 'user' })); //app.use(express_sess({ secret: 'abc', key: 'user'})); app.get('/', function (req, res, next) { res.end(JSON.stringify(req.cookies)); console.log(req.session) console.log(req.cookies) }); app.listen(3000);
For cookie-session
, I always get {} in my terminal.
For express-session
, I get things like this.
req.session: { cookie: { path: '/', _expires: null, originalMaxAge: null, httpOnly: true } } req.cookie: {user: 's:aJ97vKA5CCwxqdTj0AV1siRQ.fWusS5+qfCKICtwkfrzcZ/Gq8P0Qdx/kx8mTBhoOhGU'}
It really confuses me. So how to explain the result with the basic use? And what's the difference between them? When should I use them?
This module stores the session data on the client within a cookie, while a module like express-session stores only a session identifier on the client within a cookie and stores the session data on the server, typically in a database.
Express-session - an HTTP server-side framework used to create and manage a session middleware. This tutorial is all about sessions. Thus Express-session library will be the main focus. Cookie-parser - used to parse cookie header to store data on the browser whenever a session is established on the server-side.
Cookies are client-side files on a local computer that hold user information. Sessions are server-side files that contain user data. Cookies end on the lifetime set by the user. When the user quits the browser or logs out of the programmed, the session is over.
Express. js uses a cookie to store a session id (with an encryption signature) in the user's browser and then, on subsequent requests, uses the value of that cookie to retrieve session information stored on the server.
Basically, express-session
is more abstract, it supports different session stores (like files, DB, cache and whatnot).
And cookie-session
is a simple / lightweight cookie-based (cookie is the only storage engine supported: all the session info is stored on the client, in a cookie) session implementation. This kind of sessions is probably most famous for its Rails implementation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With