I am having an issue with the browser not storing the session cookie sent from my server. My client web app is hosted on Vercel and my server app is hosted on Heroku. I use passport to sign in, which when successful, will send a session cookie to the browser. This works fine when running the app locally (i.e. Client on localhost:3000, and server on localhost:5500). However when both apps are running on remote hosting, the browser does not store the cookie.
CORS is working fine as I am able to successfully get data from my APIs.
I have tried playing with the cookie-session options (e.g. sameSite, secure, httpOnly, domain) with zero luck.
I am guessing that the cookie might be being stored under the server's URL. I had hoped that the cookie-session option 'domain' might have sorted this out, but unfortunately it did not.
Client:
https://github.com/liamliamliam/RateFlix-Client
Server:
https://github.com/liamliamliam/RateFlix-Server
Index.mjs
import 'dotenv/config';
import express from 'express';
import mongoose from 'mongoose';
import cookieSession from 'cookie-session';
import passport from 'passport';
import bodyParser from 'body-parser';
import cors from 'cors';
import './models/index.mjs';
import './services/passport.mjs';
import routes from './routes/index.mjs';
mongoose.connect(process.env.MONGODB_URI, console.log('Connected to MongoDB'));
const app = express();
app.use(
cors({
credentials: true,
origin: ['https://rateflix.vercel.app', 'http://localhost:3000']
})
);
app.use(bodyParser.json());
app.use(
cookieSession({
maxAge: 30 * 24 * 60 * 60 * 1000,
keys: [process.env.COOKIE_KEY]
})
);
app.use(passport.initialize());
app.use(passport.session());
routes(app);
app.get('/api/env', (req, res) => res.json({ env: process.env.NODE_ENV }));
const PORT = process.env.PORT || 5500;
app.listen(PORT, console.log(`Running on port ${PORT}`));
services/passport.mjs (serializeUser, deserializeUser)
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((id, done) => {
User.findById(id).then((user) => done(null, user));
});
Since everything is working fine and your client is able to fetch data from your backend without any CORS issues or whatosever, then I highly believe that the cookie is stored just fine. Are you sure that you are looking at the correct cookies? They should be stored under the URL of your web client.
Make sure that you are checking the cookies of that URL and not localhost or any other.