Utilize Typescript for managing sessions in MySQL database

I'm attempting to set up a mysql session storage in NestJS using Typescript. I've gone ahead and installed the necessary packages such as express-session, express-mysql-session, and @types/express-mysql-session. The code snippet below is compiling fine (main.ts file), however, upon running it, an error pops up in the console:

import { AppModule } from "./app.module";
import { env } from "./common/env";
import session from "express-session";
import MySQLStore from "express-mysql-session";

async function bootstrap() {
  const app = await NestFactory.create(AppModule, {
    cors: { credentials: env.ENABLE_CORS, origin: env.CLIENT_HOST },
  });

  //session store
  const options = {
    host: "db",
    port: 3306,
    user: env.DB_USER,
    password: env.DB_PASSWD,
    database: env.DATABASE,
    checkExpirationInterval: 1000 * 60 * 60 * 2,
    expiration: 1000 * 60 * 60 * 24,
  };

  const store = MySQLStore(session);
  const sessionStore = new store(options);

  app.use(
    session({
      secret: env.COOKIE_SECRET,
      store: sessionStore,
      resave: false,
      saveUninitialized: false,
      cookie: {
        httpOnly: true,
        maxAge: 1000 * 60 * 60 * 24,
      },
    }),
  );

  await app.listen(env.PORT_BACKEND || 8080);
}
bootstrap();

The specific error can be viewed here.

Even attempting to use require instead of import doesn't seem to work, like so:

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

What would be the correct approach to make this setup work? Or perhaps there's a more suitable package available for this purpose?

Answer №1

Success! Managed to get it functioning by also installing the mysql2 package, you can find out more here.

This is how the code turned out:

import { NestFactory } from "@nestjs/core";
import { env } from "./common/env";
import { AppModule } from "./modules/app/app.module";
import * as session from "express-session";
import * as MySQLStoreCreator from "express-mysql-session";
import * as mysql2 from "mysql2/promise";

async function bootstrap() {
  const app = await NestFactory.create(AppModule, {
    cors: { credentials: env.ENABLE_CORS, origin: env.CLIENT_HOST },
  });

  //session store
  const options = {
    host: "db",
    port: 3306,
    user: env.DB_USER,
    password: env.DB_PASSWD,
    database: env.DATABASE,
    checkExpirationInterval: 1000 * 60 * 60 * 2,
    expiration: 1000 * 60 * 60 * 24,
  };

  const connection = mysql2.createPool(options);
  const sessionStore = new (MySQLStoreCreator(session))({}, connection);

  app.use(
    session({
      secret: env.COOKIE_SECRET,
      store: sessionStore,
      resave: false,
      saveUninitialized: false,
      cookie: {
        httpOnly: true,
        maxAge: 1000 * 60 * 60 * 24,
      },
    }),
  );

  await app.listen(env.PORT_BACKEND || 8080);
}
bootstrap();

Perhaps this solution will benefit someone C:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with TypeScript not detecting exported Firebase Cloud Functions

Dealing With Firebase Cloud Functions Organization I am managing a large number of Firebase Cloud Functions, and in order to keep the code well-structured, I have divided them into separate files for each function category (such as userFunctions, adminFun ...

Angular: A Guide to Displaying HTML Content from a TypeScript File

I implemented jQuery dataTable to showcase data on a list view. In my attempt to populate data into the dataTable, I used the following approach. Within users.component.ts: getUsers() { this.UserService.getUsersList() .subscribe( succ ...

Is there a way to seamlessly stream a Docker container's log to a web browser using Express, without the need to constantly reload

Looking to stream your docker container log to your web browser without refreshing? Utilize express and node-docker-api for a seamless solution. Here is the current script in action: app.get('/container/:id/log', async function(req, res){ aw ...

There are occasional instances where certain users may experience difficulty accessing the Express app

Occasionally, the app becomes inaccessible to certain users even though they are on the same LAN. Some users can access it while others cannot. The web app was built using the following technologies: Node Angular Express MySql The app is hosted on AWS ...

Angular 14 now offers ngx-pinch-zoom for an enhanced zooming experience

Is it possible to add ngx-pinch-zoom to an Angular 14 project? I encountered a peer dependency conflict when trying to install pinch-zoom with --legacy-peer-deps, which worked in the project but failed in the ci/cd pipeline due to the conflict. I attempt ...

Exporting modules/namespaces to the window object in TypeScript

I have experience building APIs and applications in ES2015, but I am still learning the best practices for TypeScript. Can someone assist me with this challenge? Suppose I am creating an API/SDK for a shop. The objective is for the user to include my js f ...

The scrolling experience in Next js is not as smooth as expected due to laggy MOMENTUM

Currently, I am in the process of constructing my portfolio website using Next.js with Typescript. Although I am relatively new to both Next.js and Typescript, I decided to leverage them as a learning opportunity. Interestingly, I encountered an issue with ...

When using Mongoose populate, it may either return an empty array or a list of Object

Currently, I am honing my skills in express.js by constructing a relational API but facing difficulty in populating keys within a schema. The structure involves having a list of properties, each with associated units. The units are linked through a proper ...

Dealing with situations where an Angular component's route lacks a resolver

I have a component that handles both creating new items and updating existing ones. I have set up a Resolver for the 'edit/:id' route, but have not used one for the 'new' route. ngOnInit() { if (!(this.route.snapshot.url[0].path ...

Set the default requests header in Ionic 3 using data stored in Ionic Storage

This particular issue is related to retrieving a value from local storage. I am trying to set the default header (Authorization token) for all requests, but I can't seem to find a solution that works efficiently. Most of the resources available only e ...

What is the significance of utilizing response.json() for accessing JSON objects on both the server and client sides?

Just starting out with the MEAN stack, I've included my API code below where I'm using res.json(random) to send a random password. module.exports.changePass = function (req, res) { console.log(req.body.email) db.user.find({ where: { name: ...

Tips for utilizing ion-img within an Ionic 3 application?

I am currently developing an app using Ionic 3 that includes a large number of images spread across different pages. Initially, I used the default HTML image tag to display these images. However, this approach caused lag in the app's performance and a ...

Using Angular 8 for Filtering Firebase Data

I need to implement a filter on the titles of my stored data, but I am facing an issue where the structure of the filtered data changes. The original "key" of the data gets deleted by the filter and is replaced with an index instead. Link to repository : ...

The compatibility of return value types between the constructor signature and the call signature interface is not maintained when they are used together

I'm new to TypeScript and I'm struggling to figure out why I'm getting a type error in the code below. Can someone help me identify what's wrong? interface CallOrConstruct { new (value: string): Person (value: number): number } cla ...

Encountering an ERROR during the compilation of ./src/polyfills.ts while running ng test - Angular 6. The module build

I encountered a problem in an angular project I am working on where the karma.config was missing. To resolve this, I manually added it and attempted to run the test using the command ng test. However, during the execution, an error message appeared: [./src ...

Is there a way to change the data type of all parameters in a function to a specific type?

I recently created a clamp function to restrict values within a specified range. (I'm sure most of you are familiar with what a clamp function does) Here is the function I came up with (using TS) function clamp(value: number, min: number, max: number ...

Experiencing difficulties retrieving data when attempting to delete a header using Express

I'm trying to remove some data from my database in an angular application. When I click the delete button, I'm using the following method: function deleteFolder () { var folder = {}; console.log(folder); $http.delete ('/api/v1/fold ...

Session management functions properly in Postman, however, encountering issues when attempting to use it on a web

Working on a NodeJS project using express-session to handle sessions. When sending a post request to http://localhost:5500/login, a session is created with an additional property userid. Upon making a get request to http://localhost:5500/ using Postman, th ...

The Puppeteer software does not automatically shut down the browser once the task is complete

Currently, I have set up puppeteer on my Ubuntu server with Express and Node.js like so: var puppeteer = require('puppeteer'); var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/&ap ...

Typescript's puzzling selection of the incorrect overload

I have a method structured as shown below: class Bar { public executeInWorker(cb: () => void): void; public executeInWorker(cb: () => Promise<void>): void | Promise<void>; public executeInWorker(cb: () => void | Promise< ...