How to Manage session in node js using express and cookie parser?

Here, we will write a program to manage session using express js and cookie parser in node js. For this we need to create a file called app.js where we will also be importing few libraries which can provide us in-built function and classes to run our api’s.

app.js

const express=require('express');
const app=express();
const PORT=3000;
const session=require('express-session');
const cookieParser=require('cookie-parser');

app.use(cookieParser());
app.use(session({
    resave:true,
    saveUninitialized:true,
    secret:"secret"
}));

const user = {
    name:"rahul",
    age:"25",
    nationaity:"Indian"
};

app.get('/login',(req,res)=>{
    req.session.user=user;
    req.session.save();
    return res.send("user logged in");
});

app.get('/user',(req,res)=>{
    return res.send(req.session.user);
});

app.get('/logout',(req,res)=>{
    req.session.destroy();
    res.send("user logged out");
});

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