Search code examples
javascriptnode.jsexpressexpress-session

How can I write a module to handle ExpressJS session?


I'm new to ExpressJS (just 3 months) and I'm trying to make a project to get some hands on practice of what I have learned so far.

I have tried writing a module to handle express session. But it does not seem to work - no error as well as no response.

The code is:

var express = require("express");
var session = require('express-session');
var MySQLStore = require('express-mysql-session')(session);

// MySQL Session Configuration
const mySQLSessionConfiguration = {
    host: 'localhost',
    port: 1234,
    user: 'thisIsNotMyRealUsername',
    password: 'neitherThisIsMyRealPassword',
    database: 'aDatabase'
};

// Create Session
module.exports = function (){
    return (session({
    store: new MySQLStore(mySQLSessionConfiguration),
    secret: 'LOL',
    resave: true,
    saveUninitialized: true
    }));
};

and in my index.js file:

app.use(require("./modules/session.js"));

// The code works fine if I write this directly inside the index.js but I want to write a module - I wanna learn.

Error in CLI: none Error in Browser: none but nothing. I mean neither a response. Keeps waiting

Whats wrong here. Any help will be appreciated. Thanks


Solution

  • I have fixed the problem by passing the "app" directly into the module instead of returning the session from the module.

    The fixed code looks like this:

    // var express = require("express"); -- not required at all
    var session = require('express-session');
    var MySQLStore = require('express-mysql-session')(session);
    
    // MySQL Session Configuration
    const mySQLSessionConfiguration = {
        host: 'localhost',
        port: 1234,
        user: 'thisIsNotMyRealUsername',
        password: 'neitherThisIsMyRealPassword',
        database: 'aDatabase'
    };
    
    // Create Session
    module.exports = function (app){    // app received :D
        app.use(session({               // app.use instead of return
        store: new MySQLStore(mySQLSessionConfiguration),
        secret: 'LOL',
        resave: true,
        saveUninitialized: true
        }));
    };
    

    and in index.js

    var alpha = require("./modules/session.js")(app);