Is it possible to utilize RedisJson to store express-session data in place of Redis?

I am currently attempting to access the express-session data manually without relying on req.session.reload() and req.session.save(). My aim is to utilize Redisjson instead of the default redis. The problem I am encountering is that the express-session sets data using .get() rather than .json.get() (.get saves it as a string, preventing me from accessing the session through client.json.get().

In the express-session session.js file, the store is saved using:

defineMethod(Session.prototype, 'save', function save(fn) {
  this.req.sessionStore.set(this.id, this, fn || function(){});
  return this;
});

I have set up the store with the following code:

const RedisStore = require("connect-redis").default;
const { createClient } = require("redis");
require("dotenv").config();

const RedisClient = createClient({
    url: `redis://localhost:${process.env.REDISPORT}`
});

RedisClient.connect();
const store = new RedisStore({ client: RedisClient });
const RedisJsonGet = RedisClient.json.get.bind(RedisClient.json);
const RedisJsonSet = RedisClient.json.set.bind(RedisClient.json);


const sessionmiddleware = session(
    {
    store: store,
    secret: crypto.randomBytes(32).toString("hex"),
    resave: false,
    saveUninitialized: true
    }
)

I am able to access RedisClient.json methods as demonstrated in RedisJsonGet and Set, but when trying to access them within express-session, they are undefined.

Is there a way for me to access them within express-session?

Answer №1

Last year, I encountered a similar issue and developed a module that functions like connect-redis but utilizes JSON.

https://github.com/guyroyse/connect-redis-stack

Although this may seem like self-promotion, my software effectively addresses the problem you are facing. While I have not actively maintained or marketed it, it serves its purpose well. Feel free to make use of it if it proves beneficial to you.

Answer №2

The solution has been discovered! The necessary actions involve modifying the functions within the RedisStore class:

const RedisJsonGet = RedisClient.json.get.bind(RedisClient.json);
const RedisJsonSet = RedisClient.json.set.bind(RedisClient.json);
const RedisJsonDel = RedisClient.json.del.bind(RedisClient.json);

class RedisJsonStore extends RedisStore {
    constructor(options = {}) {
        super(options);
    }

    async get(sid, cb) {
        try {
        const sessionData = await RedisJsonGet(`sess:${sid}`);
        cb(null, sessionData);
        } catch (err) {
        cb(err);
        }
    }

    async set(sid, sessionData, cb) {
        try {
        await RedisJsonSet(`sess:${sid}`, '.', sessionData);
        cb(null);
        } catch (err) {
        cb(err);
        }
    }

    async destroy(sid, cb) {
        try {
        await RedisJsonDel(`sess:${sid}`);
        cb(null);
        } catch (err) {
        cb(err);
        }
    }
}
  
const store = new RedisJsonStore({client: RedisClient});

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

Nested ng-repeats within ng-repeats

I have a question regarding the correct way to utilize an inner ng-repeat inside of an outer ng-repeat: Essentially, I am looking to implement something along these lines: <tr ng-repeat="milestone in order.milestones"> <td>{{mi ...

Struggling with the alignment of pictures inside a container

I utilized the Instafeed.js library to fetch the three most recent images from an Instagram account. These images are loaded into a specific div and I successfully customized their styling according to my requirements. However, the current setup is quite s ...

Issues with Login and Register functionality in a node.js application using MongoDB

I am facing an issue with my app.js. After registering for a new account, it should send the data to MongoDB and then take me directly to page2. However, instead of that, it redirects me back to the home page. Moreover, when I try to log in by entering my ...

Obtain the string value of `reader.result` from the `FileReader

Struggling to retrieve a string in a reader.onloadend but it's constantly returning my entire function. Here is the function I'm using: uploadFile() { let vm = this; var file = vm.$refs["testeLogo"].files[0]; var reade ...

Ways to efficiently transmit pre-designed HTML components from a WebMethod to jQuery

I'm currently working on implementing infinite scrolling on my ASP.NET C# Website. In the past, I used a somewhat cumbersome method involving the ListView Control to achieve lazy scrolling, but I'm looking for a more efficient solution this time. ...

Is it possible that data scraping with puppeteer consistently retrieves information solely from the initial page?

I'm facing an issue while trying to extract data from a website using puppeteer. Whenever I make a request for data, it always returns the information from the first page, even if I specify a different URL. Strangely, when I manually search for the sa ...

How can dependencies be conditionally imported in a module that is shared between React (Next.js) and React Native?

I am looking to create a shared Typescript module that can be used in both a React (Next.js) web app and React Native mobile apps. This module will be responsible for managing communication with the backend (Firebase) and handling state management using t ...

Creating a list using variables through a Post Request in Express

I am currently exploring how to create a list using a Post Request in Express. I am fetching Video Game data from an API and aiming to use this data to populate specific details within a list. For illustration: let name = localStorage.getItem("name"); let ...

Alter the configuration of a JSON object

I'm currently working on modifying the following JSON text. It has the structure as shown below: { "cabecera": { "tipo_cambio": "", "fecha_emision": "", "total": "" }, "detalle": { "940b130369614bd6b687dc5b41623439": { " ...

How to Specify ContentType for a New Window in JavaScript after Submitting MVC Form

When a link is clicked, I want to open a new window with content determined by a post to my MVC controller. Here's how I currently approach it: jQuery.ajax({ type: "POST", url: '/controller/mycontroller', data: { myd ...

What is the best approach to establish multiple global prefixes in a NestJS project?

I am looking to define multiple Global Prefixes for my application such as: admin/products admin/users admin/... api/products api/search api/... shop/products shop/cart shop/... In the main.ts file, I can set a single global prefix using th ...

Exploring recommendations using AngularJS

I am currently working on replicating the search suggestion feature found at: where certain words are displayed as you type in the search box. Here is my HTML setup: <form ng-controller="SearchCtrl"> <input name="q" ng-model="query" ng-keyp ...

What is the method to trigger a function upon opening an anchor tag?

When a user opens a link in my React app, I need to send a post request with a payload to my server. My current strategy involves using the onClick and onAuxClick callbacks to handle the link click event. However, I have to filter out right-clicks because ...

Having trouble importing Tone.js in your Next.js project?

Having trouble importing Tone in my Next.js project. Despite having Tone as a dependency, I face an issue when trying to run import * as Tone from 'tone'. Next.js shows an error stating it can't locate the module node_modules/tone/build/esm/ ...

Struggles with handling asynchronous events in Angular

I'm currently working on a piece of code that iterates through an array containing 10 items. For each item, a request is made and the returned data is stored in another array. The entire process goes smoothly until reaching the line that contains $q.a ...

Retrieving information from MongoDB database and displaying it in a Jade file

I'm trying to retrieve all the date values from my MongoDB database without any duplicates. I want to group them by day, month, and year so that each date is only displayed once. var mongoose = require('mongoose'); var chatSchema = mongoose ...

Ways to display additional selected values in a select menu

I have a basic form on my website that includes options like: Select 1 and Select 2. I would like to set it up so that if I select value Home in Select 1, the value in Select 2 changes to something like residence. How can I achieve this using a database? ...

Attach onClick event when employing a higher order component

Just getting started with React and I have a question. After following some blog posts, I was able to create a page using higher order components and componentDidMount to fetch data from an API and display it. Everything works smoothly and the code looks ...

Ignore missing values when performing an upsert operation

I'm currently utilizing pg-promise to manage my Postgres queries, but I've hit a roadblock with the following query conundrum: My goal is to develop a single method that can batch upsert multiple rows simultaneously. Here's the code snippet ...

Showing dynamic icons in Angular 2 applications

My goal is to dynamically load a part of my website, specifically by using icon classes defined in the interface like this: import { OpaqueToken } from "@angular/core"; import {IAppConfig} from './app.interface' export let APP_CONFIG = new Opaq ...