React.js Passport.js session and cookie problem

That’s my db session also passport.js configuration in index.js file:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const connect = async () => {
try {
await mongoose.connect(process.env.DB_URL);
console.log("Connected to mongoDB.");
} catch (error) {
throw error;
}
};
// Configure session store
const sessionStore = new MongoStore({
uri: process.env.DB_URL,
collection: 'Sessions',
});
app.set('trust proxy', 1); // Trust first proxy
app.use(session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
store: sessionStore,
cookie: {
secure: true,
httpOnly: true,
sameSite: 'none',
domain: 'example.com',
path: '/',
maxAge: 1000 * 60 * 5, // 5 minutes
},
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(cors({
origin: 'https://example.com',
credentials: true,
}));
require("./src/config/passportLocal")(passport)
</code>
<code>const connect = async () => { try { await mongoose.connect(process.env.DB_URL); console.log("Connected to mongoDB."); } catch (error) { throw error; } }; // Configure session store const sessionStore = new MongoStore({ uri: process.env.DB_URL, collection: 'Sessions', }); app.set('trust proxy', 1); // Trust first proxy app.use(session({ secret: process.env.SESSION_SECRET, resave: false, saveUninitialized: false, store: sessionStore, cookie: { secure: true, httpOnly: true, sameSite: 'none', domain: 'example.com', path: '/', maxAge: 1000 * 60 * 5, // 5 minutes }, })); app.use(passport.initialize()); app.use(passport.session()); app.use(cors({ origin: 'https://example.com', credentials: true, })); require("./src/config/passportLocal")(passport) </code>
const connect = async () => {
    try {
        await mongoose.connect(process.env.DB_URL);
        console.log("Connected to mongoDB.");
    } catch (error) {
        throw error;
    }
};

// Configure session store
const sessionStore = new MongoStore({
    uri: process.env.DB_URL,
    collection: 'Sessions',
});

app.set('trust proxy', 1); // Trust first proxy
app.use(session({
    secret: process.env.SESSION_SECRET,
    resave: false,
    saveUninitialized: false,
    store: sessionStore,
    cookie: {
        secure: true,
        httpOnly: true,
        sameSite: 'none',
        domain: 'example.com',
        path: '/',
        maxAge: 1000 * 60 * 5, // 5 minutes
    },
}));

app.use(passport.initialize());
app.use(passport.session());

app.use(cors({
    origin: 'https://example.com',
    credentials: true,
}));
require("./src/config/passportLocal")(passport)

`

I have a route like that:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>app.use("/api/v1/auth", authRoute);
</code>
<code>app.use("/api/v1/auth", authRoute); </code>
app.use("/api/v1/auth", authRoute);

`

That’s my login method in authRoute file

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>router.post("/login", checkUnLogin, validateSignin, login)
</code>
<code>router.post("/login", checkUnLogin, validateSignin, login) </code>
router.post("/login", checkUnLogin, validateSignin, login)

`

That’s my login controller method

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const login = async (req, res, next) => {
passport.authenticate('local', (err, user, info) => {
if (err) {
console.error(err);
return res.status(500).json({ error: 'An error occurred during authentication.' });
}
if (!user) {
return res.status(401).json(info); // Pass along the error message from LocalStrategy
}
req.login(user, (loginErr) => {
if (loginErr) {
console.error(loginErr);
return res.status(500).json({ error: 'An error occurred during login.' });
}
return res.status(200).json({ success: 'User has been logged in successfully!', img: user.img });
});
})(req, res, next);
};
</code>
<code>const login = async (req, res, next) => { passport.authenticate('local', (err, user, info) => { if (err) { console.error(err); return res.status(500).json({ error: 'An error occurred during authentication.' }); } if (!user) { return res.status(401).json(info); // Pass along the error message from LocalStrategy } req.login(user, (loginErr) => { if (loginErr) { console.error(loginErr); return res.status(500).json({ error: 'An error occurred during login.' }); } return res.status(200).json({ success: 'User has been logged in successfully!', img: user.img }); }); })(req, res, next); }; </code>
const login = async (req, res, next) => {
    passport.authenticate('local', (err, user, info) => {
        if (err) {
            console.error(err);
            return res.status(500).json({ error: 'An error occurred during authentication.' });
        }
        if (!user) {
            return res.status(401).json(info); // Pass along the error message from LocalStrategy
        }

        req.login(user, (loginErr) => {
            if (loginErr) {
                console.error(loginErr);
                return res.status(500).json({ error: 'An error occurred during login.' });
            }

            return res.status(200).json({ success: 'User has been logged in successfully!', img: user.img });
        });
    })(req, res, next);
};

`

Also it’s my passportLocal configuration:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const bcrypt = require('bcrypt');
const User = require("../model/User");
module.exports = function(passport) {
passport.use(new LocalStrategy(
async (username, password, done) => {
try {
const user = await User.findOne({ username: username });
if (!user) {
return done(null, false, { message: 'Incorrect username.' });
}
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) {
return done(null, false, { message: 'Incorrect password.' });
}
if (!user.emailVerified) {
return done(null, false, { message: 'Email not verified.' });
}
return done(null, user);
} catch (err) {
return done(err);
}
}
));
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser(async (id, done) => {
try {
const user = await User.findById(id);
done(null, user);
} catch (err) {
done(err);
}
});
};
</code>
<code>const passport = require('passport'); const LocalStrategy = require('passport-local').Strategy; const bcrypt = require('bcrypt'); const User = require("../model/User"); module.exports = function(passport) { passport.use(new LocalStrategy( async (username, password, done) => { try { const user = await User.findOne({ username: username }); if (!user) { return done(null, false, { message: 'Incorrect username.' }); } const isMatch = await bcrypt.compare(password, user.password); if (!isMatch) { return done(null, false, { message: 'Incorrect password.' }); } if (!user.emailVerified) { return done(null, false, { message: 'Email not verified.' }); } return done(null, user); } catch (err) { return done(err); } } )); passport.serializeUser((user, done) => { done(null, user.id); }); passport.deserializeUser(async (id, done) => { try { const user = await User.findById(id); done(null, user); } catch (err) { done(err); } }); }; </code>
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const bcrypt = require('bcrypt');
const User = require("../model/User");

module.exports = function(passport) {
    passport.use(new LocalStrategy(
        async (username, password, done) => {
            try {
                const user = await User.findOne({ username: username });
                if (!user) {
                    return done(null, false, { message: 'Incorrect username.' });
                }
                const isMatch = await bcrypt.compare(password, user.password);
                if (!isMatch) {
                    return done(null, false, { message: 'Incorrect password.' });
                }
                if (!user.emailVerified) {
                    return done(null, false, { message: 'Email not verified.' });
                }
                return done(null, user);
            } catch (err) {
                return done(err);
            }
        }
    ));

    passport.serializeUser((user, done) => {
        done(null, user.id);
    });

    passport.deserializeUser(async (id, done) => {
        try {
            const user = await User.findById(id);
            done(null, user);
        } catch (err) {
            done(err);
        }
    });
};

`

When I run this application in localhost everything is okay.

but I have deployed API also frontend(React.js).

after login in production I send request to the /auth/test route

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>{
"isAuthenticated": false,
"user": "User yoxdu",
"session": {
"cookie": {
"originalMaxAge": 300000,
"expires": "2024-05-19T20:21:58.010Z",
"secure": true,
"httpOnly": true,
"domain": "example.com",
"path": "/",
"sameSite": "none"
}
}
}
req.user is not defined but in my DB session created
</code>
<code>{ "isAuthenticated": false, "user": "User yoxdu", "session": { "cookie": { "originalMaxAge": 300000, "expires": "2024-05-19T20:21:58.010Z", "secure": true, "httpOnly": true, "domain": "example.com", "path": "/", "sameSite": "none" } } } req.user is not defined but in my DB session created </code>
{
"isAuthenticated": false,
"user": "User yoxdu",
"session": {
"cookie": {
"originalMaxAge": 300000,
"expires": "2024-05-19T20:21:58.010Z",
"secure": true,
"httpOnly": true,
"domain": "example.com",
"path": "/",
"sameSite": "none"
}
}
}

req.user is not defined but in my DB session created

Backend and Frontend are HTTPS also cors configuration is okay there is not problem in there

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