title: i am not getting req.session in error handling middleware my Node and express app?
body: <p>this is the error and undefined i am getting , when i console.log (req.session) and accessing req.session.isLoggedIn in my error handling middleware</p>
  <pre><code>  cookie: {
      path: '/',
      _expires: null,
      originalMaxAge: null,
      httpOnly: true,
      secure: null,
      domain: null,
      sameSite: null
    },
    csrfSecret: 'TAmB7luZ3vUTFd0FWmsWoXHP',
    flash: {},
    isLoggedIn: true,
    user: {
      cart: { items: [] },
      _id: 5f1adb6163d0bc36506a6696,
      email: 'bella@gmail.com',
      password: '$2a$12$HCaoOhpMJiBEIw177tR4LuMV62a3zlnWFz4RQZYH4TPzit/vYRfn2',
      __v: 1
    }
  }
  undefined
  TypeError: Cannot read property 'isLoggedIn' of undefined
      at D:\Node-Project\app.js:110:34
      at Layer.handle_error (D:\Node-Project\node_modules\express\lib\router\layer.js:71:5)
      at trim_prefix (D:\Node-Project\node_modules\express\lib\router\index.js:315:13)
      at D:\Node-Project\node_modules\express\lib\router\index.js:284:7
      at Function.process_params (D:\Node-Project\node_modules\express\lib\router\index.js:335:12)
      at next (D:\Node-Project\node_modules\express\lib\router\index.js:275:10)
      at Layer.handle_error (D:\Node-Project\node_modules\express\lib\router\layer.js:67:12)
      at trim_prefix (D:\Node-Project\node_modules\express\lib\router\index.js:315:13)
      at D:\Node-Project\node_modules\express\lib\router\index.js:284:7
      at Function.process_params (D:\Node-Project\node_modules\express\lib\router\index.js:335:12)
      at next (D:\Node-Project\node_modules\express\lib\router\index.js:275:10)
      at Layer.handle_error (D:\Node-Project\node_modules\express\lib\router\layer.js:67:12)
      at trim_prefix (D:\Node-Project\node_modules\express\lib\router\index.js:315:13)
      at D:\Node-Project\node_modules\express\lib\router\index.js:284:7
      at Function.process_params (D:\Node-Project\node_modules\express\lib\router\index.js:335:12)
      at next (D:\Node-Project\node_modules\express\lib\router\index.js:275:10)
  </code></pre>
  <p><em>this is error i am  getting in above</em></p>
  <pre><code>    const express = require('express');
      const session = require('express-session');
      const MongoDbStore = require('connect-mongodb-session')(session);
      const csrf = require('csurf');
      const flash = require('connect-flash');
      const multer = require('multer');
      const bodyParser = require('body-parser');
      const app = express();
      const MONGODB_URI =
        '***************************************';
      const store = new MongoDbStore({
        uri: MONGODB_URI,
        collection: 'sessions',
      });
      const csrfProtection = csrf();
      const fileStorage = multer.diskStorage({
        destination: (req, file, cb) =&gt; {
          cb(null, 'images');
        },
        filename: (req, file, cb) =&gt; {
          cb(null, new Date().toISOString() + '-' + file.originalname);
        },
      });
      const fileFilter = (req, file, cb) =&gt; {
        if (
          file.mimetype === 'image/png' ||
          file.mimetype === 'image/jpg' ||
          file.mimetype === 'image/jpeg'
        ) {
          cb(null, true);
        } else {
          cb(null, false);
        }
      };
      app.set('view engine', 'ejs');
      app.set('views', 'views');
      const adminRoutes = require('./routes/admin');
      const shopRoutes = require('./routes/shop');
      const authRoutes = require('./routes/auth');
      
      const errorController = require('./controllers/errors');
      app.use(bodyParser.urlencoded({ extended: false }));
      app.use(
        multer({ storage: fileStorage, fileFilter: fileFilter }).single('image')
      );
      app.use(
        session({
          secret: 'my secret',
          resave: false,
          saveUninitialized: false,
          store: store,
        })
      );
      app.use(csrfProtection);
      app.use(flash());
      app.use((req, res, next) =&gt; {
        res.locals.isAuthenticated = req.session.isLoggedIn;
        res.locals.csrfToken = req.csrfToken();
        console.log(req.session);
        next();```
              ` ***in this middleware i can access my req.session***`
  &gt;In this middleware i can access my req.session
      ```});    
      app.use((req, res, next) =&gt; {
        if (!req.session.user) {
          return next();
        }
        User.findById(req.session.user._id)
          .then((user) =&gt; {
            if (!user) {
              return next();
            }
            req.user = user;
            next();
          })
          .catch((err) =&gt; {
            next(new Error(err));
          });
      });    
      app.use('/admin', adminRoutes);
      app.use(shopRoutes);
      app.use(authRoutes);
      app.use(express.static(path.join(__dirname, 'public')));
      app.use('/500', errorController.get500);
      app.use(errorController.get404);
      app.use((error, req, res, next) =&gt; {```
              `***in this middleware i am getting undefined on accessing req.session***`
      console.log(req.session);      ```
      res.status(500).render('500', {
              docTitle: 'Error!',
              path: '/500',
              isAuthenticated: req.session.isLoggedIn,
            });
          });
      const User = require('./models/user');
      const mongoose = require('mongoose');
      const { error } = require('console');
      mongoose
        .connect(MONGODB_URI, { useNewUrlParser: true, useUnifiedTopology: true })
        .then((result) =&gt; {
          app.listen(3000);
        })
        .catch((err) =&gt; console.log(err));
  </code></pre>
  <p>In this above code i am developing a simple Node and  express app
  in which in error handling middleware i can't access my req.session
  ,but i can access it in the above middlewares . there is no session in my error handling middleware,please help me how to write code diffensively</p>