WriterState
WriterState

Reputation: 369

Cookies Only set in Chrome - not set in Safari, Mobile Chrome, or Mobile Safari

I have a working sign up and sign in end point when using desktop browsers (only Chrome), but when trying to sign up or sign in using a mobile browser, the server times out. I suspect this is because my session cookies and csurf cookies are not being sent over with my fetch request.

I have opened Safari development on my mobile browser, and it does not show any cookies. I suspect now that this is because of MaxAge --

Note that my api and client are on separate domains, Heroku and Netlify. See the code below:

CORS Options

const options = {

  origin: "clientUrl",
  methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
  allowedHeaders: [
    "Content-Type",
    "Access-Control-Allow-Headers",
    "Access-Control-Allow-Origin",
    "Authorization",
    "csrf-token"
  ],
  exposedHeaders: [
    "Content-Type",
    "Access-Control-Allow-Headers",
    "Access-Control-Allow-Origin",
    "Authorization",
    "csrf-token"
  ],

  maxAge: 3600,
  preflightContinue: true,
  credentials: true
};

CSURF Config

app.use(
  csurf({
    cookie: true,
    domain: "clientUrl",
    sameSite: "none"
  })
);

Express Session Config

app.use(
  session({
    //This is our Encryption Key
    secret: process.env.sessionCode,
    //We set resave to false because our mongo store implements the "touch" function
    resave: false,
    //We Set saveUninitialized to false because we don't want to save unmodified
    //sessions to our mongo store
    secure: true,
    domain: "clientUrl",
    saveUninitialized: false,
    unset: "destroy",
    sameSite: "none",
    store: new MongoStore({
      mongooseConnection: mongoose.connection,
      //We encrypt out store code
      code: process.env.storeCode
    })
  })
);

Upvotes: 4

Views: 3284

Answers (1)

AndrewLeonardi
AndrewLeonardi

Reputation: 3512

After a battle I've figured this out with the help of this post Setting a domain with Express sessions stops cookie from being saved.

The issue comes down to third party cookies.

If you're sending data from server.herokuapp.com to site.herokuapp.com you're going to have this issue. The solution is to use the same custom domain for both your frontend and backend Heroku applications.

You should add a custom domain to your frontend and a subdomain to your backend Heroku application. Frontend should look like mywebsite.com and backend should look like server.mywebsite.com.

Within your DNS the subdomain should be server in this example and point to the Heroku DNS target for the backend. The frontend subdomain should be @ or www and point to the Heroku DNS target for the frontend.

Once your applications are being served from the same URL and you have cors set up you will no longer have any third party cookie issues.

You can read more about this here

Upvotes: 5

Related Questions