I am using express-session to store data pertaining to user sessions, such as sign-in state and access_tokens. I'm also using connect-session-sequelize to create a store for the session, so cookie-related information is saved to the connected table. However, my question is that even when I do not add extra columns to the session table to account for the extra data I'm storing such as the sign-in state and tokens, they still are able to persist through restarting the express server.
app.use( session( {
secret: SESSION_KEY,
resave: false,
saveUninitialized: false,
store: new sequelizeStore( {
db: db.sequelize,
table: 'sessions'
} ),
cookie: {
secure: true,
maxAge: 600000
}
} ) );
Notice in the above code I am keeping the default table and not extending it, so it only has the sid, expires and data columns which are saved when a session is generated for a user.
app.get( '/auth', async ( req, res ) => {
if ( !req.session.loggedIn ) {
//Login here and obtain Oauth2 tokens
req.session.loggedIn = true;
req.session.access_token = access_token;
req.session.save();
res.redirect( `https://localhost/servers` );
} else {
res.redirect( `https://localhost/servers` );
}
} );
In the above code, when the auth endpoint is hit it checks the session to see if it's logged in, and if not it attempts to login and set that for the session otherwise it redirects to the servers page. The loggedIn session variable is not saved to the table, yet when I hit that endpoint to get logged in for a session and then restart the express server, the session variable loggedIn persists despite not being saved to the table. How can this be? Are the sessions being stored elsewhere?
You don't need to add columns to the session table since session data is serialized as JSON (in most cases) when stored to the database, including any custom fields added to it.
When the server pulls the session from the storage it is deserialized and you can access those custom fields.
Note that if you are using connect-session-sequelize, you have the option to configure extendDefaultFields which affect your ability to query session data by those specific fields, but it is not mandatory in order to store custom fields as part of the session data object.