'Localhost accessed req.session.userid but virtual host can't be reached

here is some problem that i have... i have been tried days to figure it out but nothing make it working.

i have Node.js Express session on backend and there are users, when i make login i set req.session.userId = "userid" and i have middleware that check if req.session.userId exist and then next() so on Localhost everything worked fine but when i hosted my website i can’t access the req.session.userId it's mean the Middleware don’t next()

  • Frondend hosted: Netlify
  • Backend hosted: Nodechef
  • Mysql hosted: Nodechef

i don’t know, maybe i missed something or that i have to made some changes when hosting...

i hope you guys have solution for me 🙌🏻

index.js

const express = require('express');
const cookieParser = require("cookie-parser");
const session = require('express-session');
const cors = require('cors');

const app = express();
app.use(express.json());
app.use(cookieParser());
app.use(cors({
origin: '***********',
credentials: true
}));

app.all('/', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Credentials", true);
    next();
});

app.use(session({
    secret: "******",
    name: "*****",
    saveUninitialized: true,
    resave: true,
    cookie: {
        domain: '*******',
        secure: true,
        maxAge: 1000 * 60 * 60 * 24 * 365,
    }
}))
app.get('/', (req, res) => {
    res.send({ msg: "seccess" })
})
app.use('/users', require('./routes/users'))

const PORT = 3000
app.listen(process.env.PORT || PORT, () => {
    console.log(`Express server listening on port ${PORT} `);
});

users/login

 const router = require('express').Router()

 router.post('/login', (req, res) => {
    const { userEmail, userPassword } = req.body
    db.query(`SELECT * FROM users WHERE userEmail = ?`, userEmail,
        (err, result) => {
            if (err) {
                return res.send({ err: err })
            } else {
                if (!userEmail || !userPassword) 
                req.session.userId = user.id
                res.send({ msg: "Login Succes", req: req.session, user: user.id })
            }
        })
});

Middleware

module.exports.onlyLoggedUsers = (req, res, next) => {
    if (req.session.userId) {
        next()
    } else {
        res.status(200).send({err:"sensetive content for logged users only, plesae log in"})
    }
}


Solution 1:[1]

I just added app.enable('trust proxy') and it is work temporarily, in safari this not work and also on smartphone, if I got to setting in safari and turn of Prevent Cross-Site Tracking it is working so my question is how I can run the application without turn of Prevent Cross-Site Tracking.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tyler2P