Sessions & Cookies - rohit120582sharma/Documentation GitHub Wiki

HTTP is stateless. In order to associate a request to any other request, you need a way to store user data between HTTP requests. Cookies, URL parameters and Sessions solve this problem.

Cookies

Cookies are simple, small data stored on the client (browser) which belongs to a user and can be shared across requests.

Cookies and URL parameters are both suitable ways to exchange data between the client and the server. But they are both readable and can be manipulate on the client side.

Cookies are sent to client with a server request and stored on the client side, and then the cookie is sent with all subsequent requests made to the same server inside a Cookie HTTP header.

The Set-Cookie HTTP response header is used to send cookies from the server to the user agent which is used by Express.js under the hood.

Cookies can be configured to expire when the browser is closed ("Session Cookie") or when a certain age/expiry-date is reached.

We can use cookie-parser middleware, this property is an object that contains cookies sent by the request. If the request contains no cookies, it defaults to {}.

Install

$ npm install cookie-parser

Setup

const express = require('express');
const cookieParser = require('cookie-parser');

const app = express();
app.use(cookieParser());

Setting & configuring a Cookie

The res.clearCookie and res.cookie methods are from Express.js. They are not parsing behaviours, which is why they are not in cookie-parser module.

When you set a cookie with the HttpOnly flag, it informs the browser that this special cookie should only be accessed by the server. Any try to access the cookie from client side script is strictly forbidden.

app.get('/', (req,res) => {
    // read cookies
    console.log(req.cookies);

    let options = {
        maxAge: 1000 * 60 * 15, // would expire after 15 minutes
        httpOnly: true, // The cookie only accessible by the web server
        signed: true // Indicates if the cookie should be signed
    }

    // Set cookie
    res.cookie('cookieName', 'cookieValue', options); // options is optional
    res.send('');
});

Delete a Cookie

res.clearCookie('cookieName');


Sessions

A session can be defined as a server-side storage of information that is desired to persist throughout the user's interaction with the web site or web application.

It is great for storing sensitive data that should survive across requests.

Instead of storing information via cookies in the user's browser, only a unique identifier is stored on the client side.

You store session-id on the client (user's browser). This session-id is passed to the web server every time the browser makes an HTTP request. Information associated with the client is stored on the server linked to this ID.

We can use express-session middleware, this handles all things for us, i.e., creating the session, setting the session cookie and creating the session object in req object.

You can use different storages for saving your sessions on the server. The default server-side session storage, MemoryStore, is purposely not designed for a production environment. We can use connect-mongodb-session module to store sessions in MongoDB.

Install

$ npm install express-session
$ npm install connect-mongodb-session

Setup

When a user visits the site, it creates a new session for the user and assigns them a cookie. Next time the user comes, the cookie is checked and the session is provided accordingly.

const express = require('express');
const session = require('express-session');
const MongoDBStore = require('connect-mongodb-session')(session);

const app = express();
const store = new MongoDBStore(
    {
        uri: 'mongodb://localhost:27017/connect_mongodb_session_test',
        collection: 'mySessions'
    },
    function(error) {
        // Should have gotten an error when it can't connect to MongoDB
    }
);

app.use(session({
    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: false,
    store: store,
    cookie: { }
}));

Setting & configuring a Session

To store or access session data, simply use the request property req.session, which is (generally) serialized as JSON by the store, so nested objects are typically fine.

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.end()
    } else {
        req.session.views = 1;
        res.end('welcome to the session demo. refresh!');
    }
});

Delete a Session

req.session.destroy((err) => {
    // cannot access session here
    console.log(err);
    res.redirect('/');
});


⚠️ **GitHub.com Fallback** ⚠️