expressherokucorssequelize.jssequelize-cli

Netlify app can't login to Express app only on mobile


I have a Vue 3 app hosted on Netlify, and the backend is hosted on Heroku. The login is a simple /login endpoint made with Express and Sequelize. It works well on desktop, but when I try to log in on iOS, it seems the session is not being saved properly. The only thing I could find online was this, but it doesn’t provide much detail on how to fix it, other than saying to "fix CORS," which I thought I had done, but I was wrong.

Works on desktop and Android, only iOS is failing. Backend is on Heroku, frontend is on Netlify. Here is my CORS configuration:


const origins = 'http://localhost:5173,https://my-frontend.netlify.app';
const secret = 'my-secret';

app.use(session({
 secret,
 cookie: { maxAge: 3600000 },
 saveUninitialized: env !== 'production',
 resave: env !== 'production',
 secure: env === 'production',
 sameSite: 'None'
}));

const corsOptions = {
 credentials: true,
 optionSuccessStatus: 200,
 origin: origins.split(','),
}

app.use(cors(corsOptions))

app.use(function (req, res, next) {
 if(origins.split(',').includes(req.headers.origin)) {
   res.header("Access-Control-Allow-Origin", req.headers.origin);
 }
 res.header("Access-Control-Allow-Credentials", true);
 res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
 res.header("Access-Control-Allow-Headers", 'Origin,X-Requested-With,Content-Type,Accept,content-type,application/json');
 next();
});

app.use("/api/auth", authRoutes);

I've tried hitting the endpoints with Postman from my iPhone, and it works fine, so it might be an issue with the browser in ios. I can’t debug from my phone.

Just tried from Safari in desktop and I think is an issue with how I'm setting the cookie, but don't know what I'm doing wrong:

res.cookie("jwtAuth", token, {
            httpOnly: true,
            secure: process.env.NODE_ENV === 'production',
            sameSite: process.env.NODE_ENV === 'production' ? 'None' : 'Strict', 
            maxAge: 3600000
        });

I've read I COULD use localStorage to save the token and avoid this issue in IOS... but not sure if that's a good alternative.


Solution

  • I've done plenty of research on this topic. If you're facing this issue, these are your options:

    1. Host both the frontend and backend on the same hosting service.
    2. Use sessionStorage, localStorage, or your app state to save token. It's not the safest solution, but if you're working on a small application for school or just practice, it should be enough. If you're building a larger app, you should consider paying for a full hosting service for both sides.
    3. If your end users will be on Windows, then keep using cookies (although third-party cookies will likely stop working on all operating systems eventually).