Express.js - Session and Cookies
npm install --save express-session
Storing sessions in memory
This is just for development. In production we will not store sessions in memory as with lot of users it can easily crash.
We need to first add sesssion middleware.
app.js
const session = require('express-session');
const app = express();
app.use(
session({secret: 'my secret', resave: false, saveUninitialized: false })
);
//my secret in production = long string value
//resave: false and saveUninitialized: false = session will not be saved on every request, only if something change
controllers/auth.js
exports.postLogin = (req, res, next) {
req.session.isLoggedIn = true; //isLogged in is our name
res.redirect('/');
}
After postLogin
new cookie will be created in our browser, we can see it in developer console under Application/Cookies.
Storing sessions in database
npm install --save connect-mongodb-session
This is for production. We will use MongoDB for storing sessions.
app.js
const session = require('express-session');
const MongoDBStore = require('connect-mongodb-session')(session);
const MONGODB_URI = 'mongodb+srv://MONGO_USER:MONGO_PASSWORD@cluster0-gconm.mongodb.net/test?w=majority';
const app = express();
const store = new MongoDBStore({
uri: MONGODB_URI,
collection: 'sessions'
});
app.use(
session({
secret: 'my secret',
resave: false,
saveUninitialized: false,
store: store
})
);
controllers/auth.js
This remains the same, session are now stored in MongoDB.
exports.postLogin = (req, res, next) {
req.session.isLoggedIn = true; //isLoggedIn is our name
res.redirect('/');
}
exports.postLogout = (req, res, next) => {
req.session.destroy((err) => {
console.log(err);
res.redirect('/');
});
}