I am working on a project in express. I need to get certain fields from a login route into a session on the backend, so I can call the data from different routes. The problem is that when I try to access the data in a different route from where I save it, it doesn’t work. I am using cookie-session.
Below I include the relevant code
App.js:
// app.js
const express = require('express');
const cors = require('cors');
const session = require('cookie-session');
require('dotenv').config();
const app = express();
const port = process.env.PORT || 5000;
// Import MongoDB client
const client = require('./dbClient');
app.use(session({
name: 'session',
keys: [process.env.SESSION_SECRET],
}));
Auth.js
// Login route
router.post('/login', async (req, res) => {
const { usernameoremail, password } = req.body;
try {
const usersCollection = client.db('DB').collection('users');
const user = await usersCollection.findOne({
$or: [{ username: usernameoremail }, { email: usernameoremail }]
});
if (!user) {
return res.status(401).json({ message: 'Invalid credentials' });
}
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) {
return res.status(401).json({ message: 'Invalid credentials' });
}
const token = jwt.sign(
{ userId: user._id, username: user.username, email: user.email, role: user.role },
process.env.JWT_SECRET,
{ expiresIn: '1h' }
);
// Store in cookie-session
req.session.user = {
username: user.username,
email: user.email,
role: user.role,
};
It is the same for the register route.
ticketsystem.js
const express = require('express');
const router = express.Router();
// Import MongoDB client
const client = require('../dbClient');
const ticketsCollection = client.db('DB').collection('tickets');
// get user tickets
router.get('/tickets', async (req, res) => {
try {
const user = req.session.user;
const tickets = await ticketsCollection.find({ user: user.username }).toArray();
res.json(tickets);
} catch (error) {
console.error('Error fetching tickets:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
module.exports = router;
What I’ve tried
- I tried multiple libraries such as express-session and cookie parser.
- I tried multiple configurations for the middleware.
- I made sure that it was above all routes in app.py.
If anyone would be so kind to help me with this, I would really appreciate it!