Express sessions

Hello, I can’t grasp the express-session library. Here is my main server.js file:

require('dotenv').config();
const express = require('express');
const session = require('express-session');
const mongoose = require('mongoose');
const MongoStore = require('connect-mongo')(session);

const dbConnection = require('./db/db');
const SessionStore = new MongoStore({
  mongooseConnection: mongoose.connection,
  collection: 'sessions',
});

const app = express();
dbConnection(process.env.MONGO_URI);

app.use(
  session({
    secret: process.env.SESSION_SECRET,
    resave: false,
    saveUninitialized: false,
    store: SessionStore,
  })
);

app.use('/user', require('./routes/user'));

const PORT = process.env.PORT;

app.listen(PORT, () => console.log(`Server is listening on port ${PORT}`));

And here is my user file from the routes folder that handles requests to /user file (I removed parts that don’t regard topic):

router.post('/login', async (req, res) => {
  if (
    !req.headers.wodderapikey ||
    req.headers.wodderapikey !== 'PGP9X9PGaeFmQVMkV1Wt7ygfTgJyfE9kI2S0taLK'
  )
    return res.status(401).json({ msg: 'Unauthorized request' });

  const { email, password } = req.body;

  try {
    const user = await User.findOne({ email });

    if (!user) {
      return res.status(400).json({ msg: 'This email is not registered' });
    }

    const isPasswordCorrect = await bcrypt.compare(password, user.password);

    if (!isPasswordCorrect) {
      return res.status(400).json({ msg: 'Wrong password' });
    }

    req.session.email = user.email;
    res.status(200).json({ msg: 'User logged in' });
  } catch (error) {
    console.log(error);
    res.status(500).json({ msg: 'Internal server error, please try again' });
  }
});

router.post('/checkAuth', (req, res) => {});

So basically I want the session to be initialized after I’m logging in user so I attached an email property to req.session object. The session is being stored in my MongoDB Atlas.

  1. How can I access my session store inside this user.js file that is handling /user route?
  2. How can I delete specific session when for example user closed the browser or clicked the log out button?
  3. I want to create the /checkAuth route that would check if the cookie attached to the request has the session ID that is already stored in the database, I don’t have idea how could I do that.

Thank you for your time and help.

How can I access my session store inside this user.js file that is handling /user route?

just as you stored them “req.session.email”

How can I delete specific session when for example user closed the browser or clicked the log out button?

in the logout handler you can do “req.session.delete”
or in the client side you can delete the cookie

I want to create the /checkAuth route that would check if the cookie attached to the request has the session ID that is already stored in the database, I don’t have idea how could I do that.

you should just use middleware instead.

1 Like