I have scoured the community for answers, but I cant seem to find one.
In my application, I send user info from the client (react) to /user/save route. When I log the session to the console, all the data is there. But when I log req.session out on any other route it doesn't have any data.
Right now I am accessing the API from localHost while the API is hosted with ngrok.
When I had the API integrated within the same codebase as my React app, all worked well, but now it's a bit funky.
Server.js
const express = require('express');
var expressSession = require('express-session');
const cors = require('cors');
const cookieParser = require("cookie-parser");
const path = require('path');
const app = express();
const axios = require('axios');
const mongoose = require('mongoose');
const rateLimit = require("express-rate-limit");
var cron = require('node-cron');
require('dotenv').config()
const corsConfig = {
"origin": "http://localhost:3000",
"methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
"credentials": true
};
// Implemented a rate limiter which is a TEMPORARY FIX for the infinite loop by the useEffect
const limiter = rateLimit({
windowMs: .1 * 60 * 1000, // 10 seconds limit
max: 4
});
// Middleware
const hostValidationMiddleware = require('./Middleware/HostValidationMiddleware');
const sessionValidationMiddleware = require('./Middleware/SessionValidationMiddleware');
const {authenticateJWT} = require('./Middleware/JwtMiddleware');
async function connectToDB() {
// Database
await mongoose.connect(process.env.mongo_url, { useNewUrlParser: true, useUnifiedTopology: true }, () => {
console.log('[connectToDB]: Connected to DB');
})
}
connectToDB();
app.use(cookieParser());
const oneDay = 1000 * 60 * 60 * 24;
// Creating the session in order to save user data to req.session
app.use(
expressSession({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: true,
secure: false,
cookie: {
maxAge: oneDay,
sameSite: "none",
}
})
);
app.use(cors(corsConfig));
//app.use('/', limiter);
app.use(express.json());
app.use('/', hostValidationMiddleware, sessionValidationMiddleware, require('./Routes/Store-Invoices'));
app.use('/', require('./Routes/SaveLoggedInUser') , authenticateJWT, require('./Routes/GetUserInvoices'));
app.use('/', require('./Routes/UpdateUserData'));
app.get('/', async (req, res) => {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
app.listen(8081, () => {
console.log(`Server listening on 8081`);
});
Saved Logged In User
saveLoggedInUser.post('/user/save', async (req, res) => {
const User = req.body;
const token = await GetJwt(User);
req.session.currentUser = User;
if (token && !('authorization' in req.session) && User) {
req.session.authorization = `Bearer ${token}`
req.session.save();
}
console.log('USER', req.session);
const usersFromDB = await fetchUsersFromDB().catch((e) => { console.log(e) });
findCommonUser(usersFromDB,User);
res.sendStatus(200);
})
Get User Invoices
userInvoices.get('/invoice/user', async (req,res) => {
const invoices = await InvoiceModel.find().catch((e) => {console.log(e)});
const user = req.session;
console.log('INVOICE',user);
});
Client Call
async function fetchUserInvoices() {
// Making a call to external api
const url = `https://f604-104-49-198-21.ngrok.io/invoice/user`;
const invoiceResponse = await axios.get(url, {withCredentials: true}).catch((e) => { console.log(e) });
setData(invoiceResponse.data);
return;
}