Express JS session

Learn Express JS session

Hi, In this chapter you will learn how to save session with the Express JS.


Save sessions with the cookie-session module

The cookie-session is simple cookie-based session middleware. This module stores the session data on the client within a cookie.

Install

npm install cookie-session --save

After installing the cookie-session, import this module in your app and then apply this module as middleware.


Apply

const express = require('express');
const cookieSession = require('cookie-session');
const app = express();

app.use(cookieSession(options));

The options is an object that contains some options. Click here to check all the options.


index.js

const express = require('express');
const cookieSession = require('cookie-session');
const app = express();

app.use(cookieSession({
    name: 'session',
    keys: ['key1', 'key2'],
    maxAge:  60 * 1000
}));

app.get('/', (req, res) => {

    if(req.session.name){
        res.send(req.session.name);
    }
    else{
        req.session.name = 'Webtutorials.ME';
        res.send(req.session.name);
    }
});

app.listen(3000, () => console.log('Your app listening on port 3000'));
name:The name is used to set the name of the cookie
keys:The list of keys to use to sign & verify cookie values. Set cookies are always signed with keys[0], while the other keys are valid for verification
maxAge:Used to set the expiry time of the cookie or you can use also expires:

Set session:

req.session.sessionName = 'value';

Get session:

req.session.sessionName;

Destroy session:

req.session = null

Extra:

Save sessions with the express-session module

The express-session module is not the same as the cookie-session module.

This module stores only a session identifier on the client within a cookie and stores the session data on the server.

It is basically used to store session data in a database. But by default this module stores session data in MemoryStore.

If you want to store session data in a database then you can use it otherwise never use this in production environments. Because It will leak your memory under the most conditions, does not scale past a single process, and is meant for debugging and developing.

Learn – express-session


Next is – Expres JS File Upload

Previous is – Express JS Cookie

Leave a Reply

Your email address will not be published. Required fields are marked *