Websites runs on HTTP Protocol. 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 server. We can store the user’s session in database, files or server memory. In this tutorial we will learn how to use session in Node.js.
How sessions works
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 stores 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.
Create a Node Project and Initialize
npm init –y
Now Install Express
npm install express express-session cookie-parser
Set the Express Session Options
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
}));
Create and Use Session in Node.js
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');
});
That’s it like this way you can create and understood how to use session in Node.js.
Please like share and give positive feedback to motivate me to write more.
For more tutorials visit my website.
Thanks:)
Happy Coding:)
Top comments (0)