Open In App

How to handle sessions in Express ?

ExpressJS is a small framework that works on top of Node web server functionality to simplify its APIs and add helpful new features. It makes it easier to organize your application’s functionality with middleware and routing. It adds helpful utilities to Node HTTP objects and facilitates the rendering of dynamic HTTP objects.

To handle sessions in Express JS:

Syntax:

npm install express-session
const express = require('express');
const session = require('express-session');
const app = express();
app.use(session({
secret: 'your-secret-key',
resave: false,
saveUninitialized: false
}));
app.get('/login', (req, res) => {
// Set session data
req.session.user =
{ id: 1, username: 'example' };
res.send('Logged in');
});
app.get('/profile', (req, res) => {
// Access session data
const user = req.session.user;
res.send(`Welcome ${user.username}`);
});
app.get('/logout',
(req, res) => {
// Destroy session
req.session.destroy((err) => {
if (err) {
console.error(err);
res.status(500).send('Error logging out');
} else {
res.send('Logged out');
}
});
});
const session = require('express-session');
const MongoStore = require('connect-mongo')(session);
app.use(session({
secret: 'your-secret-key',
resave: false,
saveUninitialized: false,
store: new MongoStore(
{
url: 'mongodb://localhost/session-store'
}
)
}));
app.use(session({
secret: 'your-secret-key',
resave: false,
saveUninitialized: false,
cookie: {
secure: true,
// Enable only for HTTPS
httpOnly: true,
// Prevent client-side access to cookies
sameSite: 'strict'
// Mitigate CSRF attacks
}
}));

By following these steps, you can effectively handle sessions in your ExpressJS application, allowing you to maintain user state and provide personalized experiences for your users.



Example: Below is the example to handle session in ExpressJS.




const express = require('express');
const session = require('express-session');
 
const app = express();
 
// Set up session middleware
app.use(session({
    secret: 'mySecretKey', // used to sign the session ID cookie
    resave: false, // do not save the session if it's not modified
    // do not save new sessions that have not been modified
    saveUninitialized: false
}));
 
// Middleware to log session data
app.use((req, res, next) => {
    console.log('Session:', req.session);
    next();
});
 
// Route to set session data
app.get('/set-session', (req, res) => {
    req.session.user = { id: 1, username: 'GfG User' };
    res.send('Session data set');
});
 
// Route to get session data
app.get('/get-session', (req, res) => {
    if (req.session.user) {
        res.send('Session data: '
            + JSON.stringify(req.session.user));
    } else {
        res.send('No session data found');
    }
});
 
// Route to destroy session
app.get('/destroy-session', (req, res) => {
    req.session.destroy((err) => {
        if (err) {
            console.error('Error destroying session:', err);
            res.send('Error destroying session');
        } else {
            res.send('Session destroyed');
        }
    });
});
 
// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server is listening on port ${PORT}`);
});

Output:



Output


Article Tags :