Most Popular Tutorials
Most Popular Tutorials :-

Simply Easy Learning at Your Fingertips. Click Tutorials Menu to view More Tutorial List





How to set and get session data in node.js?

What is session in node.js?

express-session module is used for manage the user session in ExpressJs. A session will contain some unique data about that client to allow the server to keep track of the user’s state. In session-based authentication, the user’s state is stored in the server’s memory or a database.

session saving the data in the key-value form.

Installation of express-session module:

npm install express-session
################ OR ##############
npm install express express-session cookie-parser

npm version express-session

File Name :

var session = require('express-session')

How To Set Session Data Using Express Session ?

var sessionData
app.get('/set_session',function(req,res){
sessionData = req.session;
sessionData.user = {};
let username = "admin";
sessionData.user.username = username;
sessionData.user.salary = random.int(100, 999);
console.log("session data:username=%s and salary=%s", username, sessionData.user.salary)

// res.end('session Data : ' + sessionData.username);
res.json(sessionData.user)
});

How To Get Session Data Using Express Session ?

app.get('/get_session',function(req,res){
sessionData = req.session;
let userObj = {};
if(sessionData.user) {
userObj = sessionData.user;
}
res.json(userObj)
});

How To Destroy Session Data Using Express Session?

app.get('/destroysession',function(req,res){
sessionData = req.session;

sessionData.destroy(function(err) {
if(err){
msg = 'Error destroying session Data';
res.json(msg);
}else{
msg = 'Session destroy successfully';
console.log(msg)
res.json(msg);
}
});
});

File Name : index.js

const express = require("express")
const session = require('express-session')
const app = express()

// Port Number Setup
var PORT = process.env.port || 3000

// Session Setup
app.use(session({

// It holds the secret key for session
secret: 'Your_Secret_Key',

// Forces the session to be saved
// back to the session store
resave: true,

// Forces a session that is "uninitialized"
// to be saved to the store
saveUninitialized: true
// cookie: { secure: true }
// cookie: { maxAge: oneDay },
}))

app.get("/", function(req, res){

// req.session.key = value
req.session.name = 'Ittutorial.in'
return res.send("Session Set")
})

app.get("/session", function(req, res){

var name = req.session.name
return res.send(name)

/* To destroy session you can use
this function
req.session.destroy(function(error){
console.log("Session Destroyed")
})
*/
})

app.listen(PORT, function(error){
if(error) throw error
console.log("Server created Successfully :", PORT)
})

Secret:-

secret - unique string key used to authenticate a session. It is stored in an environment variable and can’t be exposed to the public. The key is usually long and randomly generated in a production environment.


resave:-

File Name :

takes a Boolean value. It enables the session to be stored back to the session store, even if the session was never modified during the request. The default value is true.

saveUninitialized :-

this allows any uninitialized session to be sent to the store. When a session is created but not modified, it is referred to as uninitialized.

cookie: { maxAge: oneDay }

this sets the cookie expiry time. The browser will delete the cookie after the set duration elapses. The cookie will not be attached to any of the requests in the future. In this case, we’ve set the maxAge to a single day as computed by the following arithmetic.
// creating 24 hours from milliseconds
const oneDay = 1000 * 60 * 60 * 24;

req.session

// Use the session middleware
app.use(session({ secret: 'keyboard cat', cookie: { maxAge: 60000 }}))

// Access the session as req.session
app.get('/', function(req, res, next) {
if (req.session.views) {
req.session.views++
res.setHeader('Content-Type', 'text/html')
res.write('<p>views: ' + req.session.views + '</p>')
res.write('<p>expires in: ' + (req.session.cookie.maxAge / 1000) + 's</p>')
res.end()
} else {
req.session.views = 1
res.end('welcome to the session demo. refresh!')
}
})

Session.regenerate(callback)

To regenerate the session simply invoke the method. Once complete, a new SID and Session instance will be initialized at req.session and the callback will be invoked.

req.session.regenerate(function(err) {
// will have a new session here
})

Session.destroy(callback)

Destroys the session and will unset the req.session property. Once complete, the callback will be invoked.

req.session.destroy(function(err) {
// cannot access session here
})

app.get('/logout',(req,res) => {
req.session.destroy();
res.redirect('/');
});

Session.reload(callback)

Reloads the session data from the store and re-populates the req.session object. Once complete, the callback will be invoked.

req.session.reload(function(err) {
// session updated
})

Session.save(callback)

req.session.save(function(err) {
// session saved
})

Example :-

<html>
<head>
<link rel="stylesheet" href="views/app.css">
<style>
body {
display: flex;
justify-content: center;
}

form {
display: flex;
flex-direction: column;
}

.input-field {
position: relative;
margin-top: 2rem;
}

.input-field input {
padding: 0.8rem;
}

form .input-field:first-child {
margin-bottom: 1.5rem;
}

form input[type="submit"] {
background: linear-gradient(to left, #4776E6, #8e54e9);
color: white;
border-radius: 4px;
margin-top: 2rem;
padding: 0.4rem;
}
</style> </head>
<body>
<form action="/user" method="post">
<h2>Login</h2>
<div class="input-field">
<input type="text" name="username" id="username" placeholder="Enter Username">
</div>
<div class="input-field">
<input type="password" name="password" id="password" placeholder="Enter Password">
</div>
<input type="submit" value="LogIn">
</form>
</body>
</html>

const express = require('express');
const cookieParser = require("cookie-parser");
const sessions = require('express-session');
const app = express();
const PORT = 4000;
// creating 24 hours from milliseconds
const oneDay = 1000 * 60 * 60 * 24;

//session middleware
app.use(sessions({
secret: "thisismysecrctekeyfhrgfgrfrty84fwir767",
saveUninitialized:true,
cookie: { maxAge: oneDay },
resave: false
}));

// parsing the incoming data
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

//serving public file
app.use(express.static(__dirname));

// cookie parser middleware
app.use(cookieParser());

//username and password
const myusername = 'user1'
const mypassword = 'mypassword'

// a variable to save a session
var session;


app.get('/',(req,res) => {
session=req.session;
if(session.userid){
res.send("Welcome User <a href=\'/logout'>click to logout</a>");
}else
res.sendFile('views/index.html',{root:__dirname})
});


app.post('/user',(req,res) => {
if(req.body.username == myusername && req.body.password == mypassword){
session=req.session;
session.userid=req.body.username;
console.log(req.session)
res.send(`Hey there, welcome <a href=\'/logout'>click to logout</a>`);
}
else{
res.send('Invalid username or password');
}
})

app.get('/logout',(req,res) => {
req.session.destroy();
res.redirect('/');
});


app.listen(PORT, () => console.log(`Server Running at port ${PORT}`));

Session Expiration :-

app.use(
session({
...,
cookie: {
maxAge: 30 * 24 * 60 * 60 * 1000
}
})
);

You can use expires attribute instead of maxAge. It takes Date object as value. Also, check session cookie exipres on client after they set. Maybe session ended by server

app.use(express.session(
{ secret: "secret", store: new MemoryStore(), expires: new Date(Date.now() + (30 * 86400 * 1000))
}));

app.use(express.session(
{ secret: "secret", store: new MemoryStore(), maxAge: Date.now() + (30 * 86400 * 1000)
}));

maxAge means how long the session lasts, in ms

var hour = 3600000
req.session.cookie.expires = new Date(Date.now() + hour)

expires means when the session gonna expire, ie: a date object

var hour = 3600000
req.session.cookie.maxAge = hour

Session Rolling

express-session has a rolling property that you can set. By default it's set to false. If you set the rolling property to true, it will reset expiration to maxAge.

app.use(session({
secret: 'xxx',
name: 'sessionId',
resave: true,
saveUninitialized: true,
rolling: true, // <-- Set `rolling` to `true`
cookie: {
httpOnly: true,
maxAge: 1*60*60*1000
})
}))

increasing maxAge each time the user sends a request. When the user sends a request, calculate the time remaining before the session times out, subtract this amount of time from one hour and add the result to maxAge. Alternatively you can use the expires property along with a very large maxAge:

var hour = 3600000
req.session.cookie.expires = new Date(Date.now() + hour)
req.session.cookie.maxAge = 100 * hour


whenever a request is sent, calculate expires again:


var hour = 3600000
req.session.cookie.expires = new Date(Date.now() + hour)

App.js

app.use(session({
secret: 'mahi*786',
// Forces the session to be saved
// back to the session store
// resave: true,
resave: false,
saveUninitialized: true,
// Session expires after 1 min of inactivity.
// cookie: { maxAge: 60000 }
cookie: { maxAge: 30 * 24 * 60 * 60 * 1000 }
}))

How to get all set session data in node js

File Name :

session=req.session;
console.log(req.session)
console.log(session.username);

How to get session id

File Name :

req.sessionID

How to get session id

File Name :

req.sessionID

How to get session id

File Name :

req.sessionID

User Login with session

File Name :

var escapeHtml = require('escape-html')
var express = require('express')
var session = require('express-session')

var app = express()

app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true
}))

// middleware to test if authenticated
function isAuthenticated (req, res, next) {
if (req.session.user) next()
else next('route')
}

app.get('/', isAuthenticated, function (req, res) {
// this is only called when there is an authentication user due to isAuthenticated
res.send('hello, ' + escapeHtml(req.session.user) + '!' +
' <a href="/logout">Logout</a>')
})

app.get('/', function (req, res) {
res.send('<form action="/login" method="post">' +
'Username: <input name="user"><br>' +
'Password: <input name="pass" type="password"><br>' +
'<input type="submit" text="Login"></form>')
})

app.post('/login', express.urlencoded({ extended: false }), function (req, res) {
// login logic to validate req.body.user and req.body.pass
// would be implemented here. for this example any combo works

// regenerate the session, which is good practice to help
// guard against forms of session fixation
req.session.regenerate(function (err) {
if (err) next(err)

// store user information in session, typically a user id
req.session.user = req.body.user

// save the session before redirection to ensure page
// load does not happen before session is saved
req.session.save(function (err) {
if (err) return next(err)
res.redirect('/')
})
})
})

app.get('/logout', function (req, res, next) {
// logout logic

// clear the user from the session object and save.
// this will ensure that re-using the old session id
// does not have a logged in user
req.session.user = null
req.session.save(function (err) {
if (err) next(err)

// regenerate the session, which is good practice to help
// guard against forms of session fixation
req.session.regenerate(function (err) {
if (err) next(err)
res.redirect('/')
})
})
})

app.listen(3000)

Debugging

File Name :

DEBUG=express-session npm start

set DEBUG=express-session & npm start





Previous Next


Trending Tutorials




Review & Rating

0.0 / 5

0 Review

5
(0)

4
(0)

3
(0)

2
(0)

1
(0)

Write Review Here