0

Background: In order to log out a user I need to gain access to an object redisClient located in app.js. How do I access redisClient from a module 2 levels deep? I'm not sure how to work my way back to the fresh version of redisClient from downstream of it.

From app.js

const session = require('express-session');
const redis = require('redis');
const redisClient = redis.createClient();
const RedisStore = require('connect-redis')(session);

const myEndpoints = require('./controllers/my-endpoints');
app.use(myEndpoints);

From my-endpoints.js

const router = express.Router();
const someMiddleware = require('./some-middleware');
router.get('/logout', someMiddleware.logout);

module.exports = router;

From some-middleware.js

exports.logout = function(req, res) {

    // uh oh I'm 2 layers deep.  How do I get to redisClient from here?
    redisClient.del(req.session.id, function(err, response) {
        console.log(err);
    });


    req.session.destroy(function(error) {

        if (error) res.clearCookie(process.env.SESSION_NAME);
        res.redirect('/');

    });
}
myNewAccount
  • 578
  • 5
  • 17
  • 1
    I think you can store it with `app.set('myClient', redisClient)` and then later get it with `app.get('myClient')` – Joe Jan 11 '21 at 01:07
  • 1
    [`req.app`](http://expressjs.com/en/4x/api.html#req.app) contains the `app` object so the middleware can get the app object from there. – jfriend00 Jan 11 '21 at 01:40

1 Answers1

1

Based on this answer it was an easy fix. Thanks to the comments for pointing me in this direction.

In app.js:

app.set('referenceToRedisClient', redisClient);

In some-middleware.js:

let redisClient = req.app.get('referenceToRedisClient');
await redisClient.del(req.session.id);
myNewAccount
  • 578
  • 5
  • 17