简体   繁体   中英

How does session work in express.js

I come from php background, so without any framework I simply do session_start() and after user login I'll do session['username'] = 'sam' and in every route I check whether session['username'] exist or not, else redirect them to login page.

But in express I'm seeing lots of option like in the express-session npm

var session = require("express-session");
var sessionMiddleware = session({
    secret: "secret",
    resave: true,
    saveUninitialized: true,
    maxAge:365 * 24 * 60 * 60 * 1000
});

This npm also generate cookie, why cookie come into the picture here? if you use session why do u need to use cookie? I'm confused.

HTTP is a stateless protocol. It can not identify the users or sessions by itself. So how do most languages platform do this? They generate an unique ID for that user and store that in a cookie. And they store all the session data on the server side, using that unique ID to differentiate between user sessions.

So in PHP, when you do session_start() , it generates a cookie named PHPSESSID or something similar. Then PHP stores all the session data in a file or in a database on the server, against that key. Every time the user visits the different pages, PHP reads the value of that cookie and gets the ID. Based on that ID, PHP retrieves the session data and makes them available as $_SESSION .

The same thing is true for almost all web frameworks, including express.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM