Express session is not saving data

I am trying to store information on my req.session object upon login and at a later time access this to verify if a user is logged in for middleware

I am aware there are several similar questions but after implementing their solutions, I am either unable to get any data to save on my session or I am unable to access it.

The solutions that I have seen on similar questions have been

  1. Enabling cors on my express server
  2. Setting the withCredentials parameter on my axios request to true
  3. Calling session.save() after modifying my session

I should mention I am able to get this middleware function to work as desired with Postman which leads me to believe there is something wrong with how I am making my request.

I have the following signIn route

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>router.post('/signin', async (req, res) => {
const { email, password } = req.body;
try {
const user = await User.findOne({ email });
if (!user) {
return res.status(400).send('User not found');
}
const isMatch = await bcrypt.compare(password, user.hashedPassword);
if (!isMatch) {
return res.status(400).send('Invalid credentials');
}
const sessionUser = {
id: user._id,
email: user.email,
}
req.session.user = sessionUser;
console.log('Sign in successful: ', email)
req.session.save();
res.status(200).send(req.session);
} catch (err) {
res.status(500).send('Error signing in');
}
}
</code>
<code>router.post('/signin', async (req, res) => { const { email, password } = req.body; try { const user = await User.findOne({ email }); if (!user) { return res.status(400).send('User not found'); } const isMatch = await bcrypt.compare(password, user.hashedPassword); if (!isMatch) { return res.status(400).send('Invalid credentials'); } const sessionUser = { id: user._id, email: user.email, } req.session.user = sessionUser; console.log('Sign in successful: ', email) req.session.save(); res.status(200).send(req.session); } catch (err) { res.status(500).send('Error signing in'); } } </code>
router.post('/signin', async (req, res) => {
  const {  email, password } = req.body;
  try {
    const user = await User.findOne({ email });
    if (!user) {
      return res.status(400).send('User not found');
    }

    const isMatch = await bcrypt.compare(password, user.hashedPassword);
    if (!isMatch) {
      return res.status(400).send('Invalid credentials');
    }

    const sessionUser = {
      id: user._id,
      email: user.email,
    }
  
    req.session.user = sessionUser;

    console.log('Sign in successful: ', email)
    req.session.save();
    res.status(200).send(req.session);

  } catch (err) {
    res.status(500).send('Error signing in');
  }
}

The following app.js file

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const mongoose = require('mongoose');
const authRoutes = require('./routes/auth');
const newsletterRoutes = require('./routes/newsletter');
const session = require('express-session');
const MongoStore = require('connect-mongo');
const cors = require('cors');
require('dotenv').config();
const app = express();
app.use(cors(
{
origin: "http://localhost:3000",
credentials: true,
}
));
mongoose.connect('some_db_url');
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {console.log('Connected to MongoDB');});
// Set up session middleware
app.use(session({
secret: process.env.SESSION_SECRET,
resave: false, // don't save session if unmodified
saveUninitialized: false, // don't save session if there's nothing to save
cookie: { maxAge: 24 * 60 * 60 * 1000 }, // Session cookie expiration (1 day)
store: MongoStore.create({
client: db.getClient(), // necessary option
collectionName: 'sessions',
autoRemove: 'true',
stringify: 'false',
})
}));
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false })); // parse application/x-www-form-urlencoded
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/auth', authRoutes);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
</code>
<code>const createError = require('http-errors'); const express = require('express'); const path = require('path'); const cookieParser = require('cookie-parser'); const logger = require('morgan'); const mongoose = require('mongoose'); const authRoutes = require('./routes/auth'); const newsletterRoutes = require('./routes/newsletter'); const session = require('express-session'); const MongoStore = require('connect-mongo'); const cors = require('cors'); require('dotenv').config(); const app = express(); app.use(cors( { origin: "http://localhost:3000", credentials: true, } )); mongoose.connect('some_db_url'); const db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', function() {console.log('Connected to MongoDB');}); // Set up session middleware app.use(session({ secret: process.env.SESSION_SECRET, resave: false, // don't save session if unmodified saveUninitialized: false, // don't save session if there's nothing to save cookie: { maxAge: 24 * 60 * 60 * 1000 }, // Session cookie expiration (1 day) store: MongoStore.create({ client: db.getClient(), // necessary option collectionName: 'sessions', autoRemove: 'true', stringify: 'false', }) })); app.use(logger('dev')); app.use(express.json()); app.use(express.urlencoded({ extended: false })); // parse application/x-www-form-urlencoded app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.use('/auth', authRoutes); // catch 404 and forward to error handler app.use(function(req, res, next) { next(createError(404)); }); // error handler app.use(function(err, req, res, next) { // set locals, only providing error in development res.locals.message = err.message; res.locals.error = req.app.get('env') === 'development' ? err : {}; // render the error page res.status(err.status || 500); res.render('error'); }); module.exports = app; </code>
const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const mongoose = require('mongoose');
const authRoutes = require('./routes/auth');
const newsletterRoutes = require('./routes/newsletter');
const session = require('express-session');
const MongoStore = require('connect-mongo');
const cors = require('cors');
require('dotenv').config();

const app = express();

app.use(cors(
    {
      origin: "http://localhost:3000",
      credentials: true,
    }
));

mongoose.connect('some_db_url');

const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {console.log('Connected to MongoDB');});

// Set up session middleware
app.use(session({
  secret: process.env.SESSION_SECRET,
  resave: false, // don't save session if unmodified
  saveUninitialized: false, // don't save session if there's nothing to save
  cookie: { maxAge: 24 * 60 * 60 * 1000 }, // Session cookie expiration (1 day)
  store: MongoStore.create({
    client: db.getClient(), // necessary option
    collectionName: 'sessions',
    autoRemove: 'true',
    stringify: 'false',
  })
}));

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false })); // parse application/x-www-form-urlencoded
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/auth', authRoutes);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

and on the frontend I have my handleSubmit function to sign in

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const handleSubmit = async (event) => {
event.preventDefault();
const data = new FormData(event.currentTarget);
const payload = {
email: data.get('email'),
password: data.get('password'),
}
try {
const response = await axios.post("http://localhost:8080/auth/signIn/", payload, {withCredentials: true});
if (response.status === 200) {
console.log('Login successful with ' + data);
}
} catch (error) {
if (error.response.status === 400) {
console.log('Invalid username or password');
} else {
console.error('Error while logging in', error);
}
}
};
</code>
<code>const handleSubmit = async (event) => { event.preventDefault(); const data = new FormData(event.currentTarget); const payload = { email: data.get('email'), password: data.get('password'), } try { const response = await axios.post("http://localhost:8080/auth/signIn/", payload, {withCredentials: true}); if (response.status === 200) { console.log('Login successful with ' + data); } } catch (error) { if (error.response.status === 400) { console.log('Invalid username or password'); } else { console.error('Error while logging in', error); } } }; </code>
const  handleSubmit = async (event) => {
        event.preventDefault();
        const data = new FormData(event.currentTarget);

        const payload = {
            email: data.get('email'),
            password: data.get('password'),
        }

        try {
            const response = await axios.post("http://localhost:8080/auth/signIn/", payload, {withCredentials: true});

            if (response.status === 200) {
                console.log('Login successful with ' + data);
            }
        } catch (error) {
            if (error.response.status === 400) {
                console.log('Invalid username or password');
            } else {
                console.error('Error while logging in', error);
            }
        }

    };

and lastly the following middleware function on my frontend

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>export const isLoggedIn = () => {
try {
const response = axios.get("http://localhost:8080/auth/check-auth/", {withCredentials: true});
if (response.status === 200) {
console.log('User authenticated, access granted')
return true;
}
} catch (error) {
if (error.response.status === 403) {
console.log('403: User not authenticated, access denied')
return false;
} else {
console.log('Unknown error while authenticating: ', error)
return false;
}
}
}
</code>
<code>export const isLoggedIn = () => { try { const response = axios.get("http://localhost:8080/auth/check-auth/", {withCredentials: true}); if (response.status === 200) { console.log('User authenticated, access granted') return true; } } catch (error) { if (error.response.status === 403) { console.log('403: User not authenticated, access denied') return false; } else { console.log('Unknown error while authenticating: ', error) return false; } } } </code>
export const isLoggedIn = () => {

    try {
        const response = axios.get("http://localhost:8080/auth/check-auth/", {withCredentials: true});
        if (response.status === 200) {
            console.log('User authenticated, access granted')
            return true;
        }
    } catch (error) {
        if (error.response.status === 403) {
            console.log('403: User not authenticated, access denied')
            return false;
        } else {
            console.log('Unknown error while authenticating: ', error)
            return false;
        }
    }

}

In an attempt to access stored express-session data I enabled CORS on my express server and set withCredentials: true on axios requests from my frontend but my problem persists.

New contributor

ceebee is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật