Express Session store.on is not a function

Viewed 828

I'm trying to setup express-session with KnexSessionStore. However, starting the app returns express-session errors.

app.mjs

import bodyParser from 'body-parser'
import cors from 'cors'
import dotenv from 'dotenv'
import express from 'express'
import helmet from 'helmet'
import KnexSessionStore from 'connect-session-knex'
import session from 'express-session'

import * as corsOptions from '../config/cors.mjs'

dotenv.config()

const store = new KnexSessionStore({
  sidfieldname: 'session-id',
  clearInterval: 60000,
  createtable: true,
  tablename: 'sessions',
})

const app = express()
app.use(bodyParser.json())
app.use(helmet())
app.use(
  session({
    secret: 'secret',
    cookie: {
      maxAge: 1000 * 60 * 60 * 24, // 1 Day
      httpOnly: true,
      secure: false, // Needs to be true
      sameSite: true,
    },
    resave: true,
    saveUninitialized: false,
    store,
  }),
)

When starting this code, I get

/Users/MyUserName/Sites/node/testProject/node_modules/express-session/index.js:172 store.on('disconnect', function ondisconnect() {

TypeError: store.on is not a function

I've been playing around with the code and found that adding the store to the session causes this error although I'm not sure why that is. Would be great if anyone can point out what I'm doing wrong. Cheers!

1 Answers

it seems like you have to initialize the KnexSessionStore with the session such as const knexSession = KnexSessionStore(session); and then create the store in base of that const store = new knexSession({...}), something like:

import bodyParser from 'body-parser'
import cors from 'cors'
import dotenv from 'dotenv'
import express from 'express'
import helmet from 'helmet'
import KnexSessionStore from 'connect-session-knex'
import session from 'express-session'

import * as corsOptions from '../config/cors.mjs'

dotenv.config()
const knexSession = KnexSessionStore(session);
const store = new knexSession({
  sidfieldname: 'session-id',
  clearInterval: 60000,
  createtable: true,
  tablename: 'sessions',
})

const app = express()
app.use(bodyParser.json())
app.use(helmet())
app.use(
  session({
    secret: 'secret',
    cookie: {
      maxAge: 1000 * 60 * 60 * 24, // 1 Day
      httpOnly: true,
      secure: false, // Needs to be true
      sameSite: true,
    },
    resave: true,
    saveUninitialized: false,
    store,
  }),
)

You could also try just importing it in the way of const KnexSessionStore = require('connect-session-knex')(session);

Related