paint-brush
How to Use Session in Node.jsby@readymadecode
12,697 reads
12,697 reads

How to Use Session in Node.js

by Chetan RohillaMarch 8th, 2022
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

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. We will also learn how we can use session to remember user's state at the server. Back to the page you came from: http://://://www.njs.com/node-js-session-history-passing-notes-to-the-next-page.
featured image - How to Use Session in Node.js
Chetan Rohilla HackerNoon profile picture


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.


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 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.


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');
});


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