I successfully integrated Facebook login using Passport-js and also set up Cookie-strategy for traditional username/password login on my Express-js backend with a React front-end. The backend and frontend are hosted on separate servers and domains (backend-client.com, frontend-client.com).
While everything works smoothly on localhost, I encounter issues in the stage and production environment. Not sure if it's relevant, but I'm hosting my applications on Heroku.
The problem:
After completing Facebook authentication, the Express server redirects the user to the frontend app with a JWT cookie containing user information to verify their login status.
const cookieSettings = {
domain: process.env.COOKIE_DOMAIN,
secure : (process.env.APP_MODE === 'local' ? false : true),
httpOnly : true,
};
const cookieMaxAge = {
maxAge : 14 * 24 * 60 * 60 * 1000 // 14 days, 24h, 60 min, 60 sec * miliseconds
}
router.get('/auth/facebook/', passport.authenticate('facebook'));
router.get('/auth/facebook/callback', function(req, res, next) {
passport.authenticate('facebook', async function (err, profile, info) {
if (err || !profile) {
res.redirect(`${process.env.FRONTEND_BASE_URL}?success=0`);
}
const user = await User.findOne({ facebookId : profile.facebookId });
return user.generateAuthToken().then((token) => {
res.cookie(COOKIE_NAME, token.token, {...cookieSettings, ...cookieMaxAge});
res.redirect(`${process.env.FRONTEND_BASE_URL}?success=1`);
});
})(req, res, next);
});
Despite the presence of the cookie when hitting /auth/facebook/callback: https://i.stack.imgur.com/x2zjH.png
No cookie is sent in the response headers upon returning to the frontend client.
I'm struggling to understand why this happens. Could there be some fundamental misunderstanding about how cookies work?
https://i.stack.imgur.com/kLoAN.png
Side note: When users log in with their username and password, the cookie is successfully returned. This login method uses ajax requests with Axios without any issues related to cookie settings.