NodeJs Tutorials
- NodeJs
- Install NodeJs
- Why use NodeJs
- NodeJs Process Model
- create First Application
- Run NodeJs Application
- Node.js Console
- Node.Js Modules
- URL Modules
- node.js Callback
- Node.js Events
- Upload Files
- Upload single & Multiple Files
- NodeJs File System
- NodeJs Email
- Debugging NodeJs
- .ENV
- NodeJs Mysql
- Helpers
- encription and decription in nodeJs
- Query string
- Date & Time
- Express Js
- Template Engine with Express
- MVC Pattern in Node.Js
- list of NPM Module
- Middleware
- Body Parser
- Render
- Nodemon module
- Morgan module
- Flash Message in ExpressJs
- Session
- Session store in database
- Cookies
- Helmet
- Multer
- Router: How To Use Routing In Node.Js
- App.Js
- express.json() and express.urlencoded()
- REST APIs in NodeJs
- Gloabal Objects
- Submit Form Data
- How to get Post Data in Node.js
- How to Get URL Parameters in Node.js
- How to create Node Project
- How to Insert Form Data Into the MySql Table Using Node.js
- How to fetch Data from MySQL database table using Node.js
- CRUD Example
- Await and Async
- Promises
- Login Example
- Password Encription
- How to validate Form (Form Validation) in Node.Js?
- Registration & Login form usingn Node.Js & MySql?
- Forgot & Reset Password
- File Upload in Node.Js with ExpressJs
- Resize Image Before Upload using Multer Sharp
- Upload multiple file using node.js with multer module
- Upload file using node.js with multer module
- Client IP Address
- REST API Downloading File in NodeJs
- Export and Download CSV From MySQL Database
- CRUD REST API
- CRUD REST API Example 2
- Enable HTTPS using Node
- How to send EMAIL using NodeJs?
- Dynamic dependent dropdown using NodeJs?
- Autocomplete Search
- Get and Send Data From Ajax Request
- Get and Post Data using Ajax
- Passport Authentication
- Node Js Data type
- Node Js Error
- Node Js Array Function
- Node Js String Function
- Puppeter Module
How to use Session in ExpressJs?
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 }
}))