Websites run on the HTTP Protocol. The HTTP Protocol is a stateless protocol. It means when a HTTP Request completes the browser and server communication stops. So, we use the session to maintain and remember the user’s state at the server. We can store the user’s session in database, files or server memory. In this tutorial, we will learn how to use sessions in Node.js.
When the client makes a login request to the server, the server will create a session and store it on the server-side. When the server responds to the client, it sends a cookie. This cookie will contain the session’s unique id stored on the server, which will now be stored on the client. This cookie will be sent on every request to the server. A cookie is a key-value pair that is stored in the browser. The browser attaches cookies to every HTTP request that is sent to the server.
npm init –y
npm install express express-session cookie-parser
About express session options you can read in detail here.
const oneDay = 1000 * 60 * 60 * 24;
app.use(sessions({
secret: "thisismysecrctekey",
saveUninitialized:true,
cookie: { maxAge: oneDay },
resave: false
}));
const express = require('express');
const cookieParser = require("cookie-parser");
const sessions = require('express-session');
const http = require('http');
const app = express();
const PORT = 4000;
// creating 24 hours from milliseconds
const oneDay = 1000 * 60 * 60 * 24;
//session middleware
app.use(sessions({
secret: "thisismysecrctekey",
saveUninitialized:true,
cookie: { maxAge: oneDay },
resave: false
}));
app.use(cookieParser());
app.get('/set',function(req, res){
req.session.user = { name:'Chetan' };
res.send('Session set');
});
app.get('/get',function(req, res){
res.send(req.session.user);
});
http.createServer(app).listen(3000, function(){
console.log('Express server listening on port 3000');
});
Please like share and give positive feedback to motivate me to write more.
For more tutorials please visit my website
Thanks :)
Happy Coding :)
Also Published Here